I have created a userform to submit data to the respective cells based on vba code I found on the forum that will help me and i modifies it. But it was not working as intended.
I want to match a date in textbox1 from the userform to column G, if the date is not found, add a new row and populate data into the respective columns based the values from the textboxes at different times.
Attached image. Thank you
I want to match a date in textbox1 from the userform to column G, if the date is not found, add a new row and populate data into the respective columns based the values from the textboxes at different times.
Attached image. Thank you
VBA Code:
[/
Private Sub CommandButton1_Click()
Dim targetsheet As String
targetsheet = ComboBox1.Value
' Check if targetsheet is empty, exit the sub if true
If targetsheet = "" Then
Exit Sub
End If
Dim ws As Worksheet
Set ws = Worksheets(targetsheet)
Dim Lookup As String
Dim lastRow As Long
Dim SalesClm As Integer
Dim IvfClm As Integer
Dim MomoClm As Integer
' Disable error handling temporarily
On Error Resume Next
Lookup = Me.TextBox1.Value
' Use Match function to find the lookup value in column G
lastRow = Application.Match(Lookup, ws.Range("G5:G"), 0)
SalesClm = 2
IvfClm = 3
MomoClm = 4
' Check if the lookup value was found
If Not IsError(lastRow) Then
' Insert a new row below the last used row in column G
ws.Cells(ws.Rows.Count, "G").End(xlUp).Offset(1, 0).EntireRow.Insert
lastRow = ws.Cells(ws.Rows.Count, "G").End(xlUp).Row
' Populate data into respective columns based on TextBox values
If Me.TextBox2 <> "" Then ws.Cells(lastRow, SalesClm) = Me.TextBox2.Value
If Me.TextBox3 <> "" Then ws.Cells(lastRow, IvfClm) = Me.TextBox3.Value
If Me.TextBox4 <> "" Then ws.Cells(lastRow, MomoClm) = Me.TextBox4.Value
If Me.TextBox5 <> "" Then ws.Cells(lastRow, SalesClm + 3) = Me.TextBox5.Value
If Me.TextBox6 <> "" Then ws.Cells(lastRow, IvfClm + 3) = Me.TextBox6.Value
If Me.TextBox7 <> "" Then ws.Cells(lastRow, MomoClm + 3) = Me.TextBox7.Value
If Me.TextBox8 <> "" Then ws.Cells(lastRow, SalesClm + 6) = Me.TextBox8.Value
If Me.TextBox9 <> "" Then ws.Cells(lastRow, IvfClm + 6) = Me.TextBox9.Value
If Me.TextBox10 <> "" Then ws.Cells(lastRow, MomoClm + 6) = Me.TextBox10.Value
MsgBox "Data was added successfully"
' Clear TextBox values after data insertion
With Me
.TextBox2.Value = ""
.TextBox3.Value = ""
.TextBox4.Value = ""
.TextBox5.Value = ""
.TextBox6.Value = ""
.TextBox7.Value = ""
.TextBox8.Value = ""
.TextBox9.Value = ""
.TextBox10.Value = ""
End With
End If
End Sub
Private Sub CommandButton2_Click()
Unload Me
End Sub
Private Sub UserForm_Initialize()
Dim sh As Worksheet
ComboBox1.Clear
' Fill ComboBox1 with worksheet names from the workbook
For Each sh In ThisWorkbook.Worksheets
ComboBox1.AddItem sh.Name
Next sh
End Sub
]