I'm trying to pull and update some records thru an UserForm
and I've almost got it, except for the piece of code that isn't working as intended. It's supposed to override the previous record (whatever information is found in the same row as the record found by the IDNum.
For some reason, it starts to copy the data as of column B when it should override everything as of Column A
.
Here's the code.
Private Sub RecordUpdate_Click()
Dim LastRow As Long
Dim IDNum As String
Dim rngIDNum As Range
Dim WriteRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Records")
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rngIDNum = .Range("E1:E" & LastRow)
IDNum = txtID.Value
WriteRow = Application.Match(IDNum, rngIDNum, 0)
Cells(WriteRow, 1).Select
With ActiveCell
.Offset(0, 1).Value = txtName.Value
.Offset(0, 2).Value = txtlName.Value
.Offset(0, 3).Value = txtGender.Value
.Offset(0, 4).Value = txtAge.Value
.Offset(0, 5).Value = txtID.Value
End With
End With
End Sub
It leaves intact whatever is in Column A
and copies the edited entries from B to F instead of A to E. Any inputs are greatly appreciated.
It should start with:
.Offset(0, 0).Value = txtName.Value
Setting the ColumnIndex to 1 will make it target 1 column to the right.
Also, instead of using Select
you can directly work on the object like this:
With .Cells(WriteRow, 1)
.Offset(0, 0).Value = txtName.Value
.
.
.Offset(0, 4).Value = txtID.Value
End With
Or you can also try this version of your code using Range.Find Method
.
Private Sub RecordUpdate_Click()
Dim LastRow As Long
Dim IDNum As String
Dim rngIDNum As Range
Dim ws As Worksheet
Set ws = Worksheets("Records")
' Find the ID
With ws
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
IDNum = txtID.Value
Set rngIDNum = .Range("E1:E" & LastRow).Find(IDNum, .Range("E" & LastRow))
End With
' Inform and Exit if ID doesn't exist
If rngIDNum Is Nothing Then MsgBox "ID not found": Exit Sub
' Update the values
With rngIDNum
.Offset(0, -4).Value = txtName.Value
.Offset(0, -3).Value = txtlName.Value
.Offset(0, -2).Value = txtGender.Value
.Offset(0, -1).Value = txtAge.Value
.Offset(0, 0).Value = txtID.Value
End With
End Sub
I assumed you're working on Worksheet("Records")
which you have assigned in ws
variable.