excelvbauserform

Data transfer into multiple sheets from userform


Am new to vba and am trying to transfer data into activesheet/sh.name by activating the sheet but getting error. I also need a code to display the list of months in a combox. thank you for your assistance.

enter image description here

Private Sub ComboBox1_Change()
targetSheet = ComboBox1.Value
If targetSheet = "" Then
Exit Sub
End If
Worksheets(targetSheet).Activate
lastrow = sh.Name.Cells(Rows.Count, 1).End(x1Up).Row
sh.Name.Cells(lastrow + 1, 1).Value = TextBox1.Value
sh.Name.Cells(lastrow + 1, 2).Value = TextBox2.Value
sh.Name.Cells(lastrow + 1, 3).Value = ComboBox2.Value
sh.Name.Cells(lastrow + 1, 4).Value = TextBox4.Value
MsgBox ("Data is added Successfully")
TextBox1.Value = ""
TextBox2.Value = ""
ComboBox2.Value = ""
TextBox4.Value = ""
Worksheets("MASTERSHEET").Activate
Worksheets("MASTERSHEET").Cells(1, 1).Select
End Sub

Private Sub CommandButton2_Click()
Unload UserForm1
End Sub

Private Sub UserForm_Initialize()

Dim sh As Worksheet

    ComboBox1.Clear 'Clear combobox
    For Each sh In ThisWorkbook.Worksheets
        ComboBox1.AddItem sh.Name
    Next sh

End Sub


Solution

  • This should resolve the issue related to your sheet name and qualifying:

    With sheets(targetsheet)
        dim lastRow as long:  lastRow = .cells(.rows.count,1).end(xlup).row
        .cells(lastRow+1, 1).value = Textbox1.Value 'do this for each
        '...
    End with
    

    You also do not need to "activate" the sheet to write to it.