Excel VBA 用户窗体 - Update/Override 数据

Excel VBA UserForm - Update/Override Data

我正在尝试通过 UserForm 提取和更新一些记录,我几乎已经搞定了,只是有一段代码没有按预期工作。它应该覆盖以前的记录(与 IDNum 找到的记录在同一行中找到的任何信息。

出于某种原因,当它应该覆盖 Column A 的所有内容时,它开始复制 B 列的数据。

这是代码。

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

它完整地保留了 Column A 中的所有内容,并将编辑后的条目从 B 复制到 F,而不是从 A 复制到 E。非常感谢任何输入。

开头应该是:

.Offset(0, 0).Value = txtName.Value

ColumnIndex 设置为 1 将使其指向右侧的 1 列。
此外,除了使用 Select,您还可以像这样直接处理对象:

With .Cells(WriteRow, 1)
    .Offset(0, 0).Value = txtName.Value
    .
    .
    .Offset(0, 4).Value = txtID.Value
End With

或者您也可以使用 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

我假设你正在处理你在 ws 变量中分配的 Worksheet("Records")