I`m new to VBA coding and I need to make a module that writes data on a sheet choosen by the user, and if the sheet doesn't exist the code must create it. The problem is that my code is only replacing the data when the sheet already exists.
Sub cadastro()
Dim prod As String
Dim qtu As Long
Dim dia As Long
Dim mes As Long
Dim ano As Long
Dim data As String
Dim ctrl As Boolean
Dim ultlincad As Long
Dim ultlinres As Long
Dim ctrl2 As Boolean
Dim plan As Worksheet
Dim i As Integer
i = 6
ctrl2 = True
ctrl = True
ultlincad = Planilha10.Range("b1048576").End(xlUp).Row
prod = Application.InputBox("Produto", Title:="Produto MUDAR", Type:=2)
qtu = Application.InputBox("Quantidade", Title:="Quatidade MUDAR", Type:=1)
dia = Application.InputBox("Dia", Title:="DIA MUDAR", Type:=1)
mes = Application.InputBox("Mês", Title:="MES MUDAR", Type:=1)
ano = Application.InputBox("Ano", Title:="ANO MUDAR", Type:=1)
data = dia & "/" & mes & "/" & ano
Planilha10.Cells(ultlincad + 1, 4) = data
Planilha10.Cells(ultlincad + 1, 4).HorizontalAlignment = xlCenter
Planilha10.Cells(ultlincad + 1, 4).VerticalAlignment = xlCenter
Planilha10.Cells(ultlincad + 1, 3) = qtu
Planilha10.Cells(ultlincad + 1, 3).HorizontalAlignment = xlCenter
Planilha10.Cells(ultlincad + 1, 3).VerticalAlignment = xlCenter
Planilha10.Cells(ultlincad + 1, 2) = prod
Planilha10.Cells(ultlincad + 1, 2).HorizontalAlignment = xlCenter
Planilha10.Cells(ultlincad + 1, 2).VerticalAlignment = xlCenter
For Each Sheet In ActiveWorkbook.Worksheets
ultlinres = Sheet.Range("b1048576").End(xlUp).Row
If Sheet.Name = ano Then
Do Until i = (ultlinres + 1)
Debug.Print ("passo5")
If Sheet.Cells(i, 2).Value = prod Then
Sheet.Cells(i, mes + 2).Value = Sheet.Cells(i, mes + 2).Value + qtu
Sheet.Cells(i, mes + 2).HorizontalAlignment = xlCenter
Sheet.Cells(i, mes + 2).VerticalAlignment = xlCenter
ctrl2 = False
ctrl = False
End If
i = i + 1
Loop
If ctrl2 Then
Sheet.Cells(6, 2) = prod
Sheet.Cells(6, mes + 2).Value = qtu
ctrl = False
End If
End If
Next Sheet
If ctrl Then
Set plan = ActiveWorkbook.Sheets.Add
plan.Name = ano
plan.Cells(6, 2) = prod
plan.Cells(6, mes + 2).Value = qtu
End If
End Sub