我有一个主表,我需要客户能够使用工作表进行更新,在该工作表中,客户将为其设置的每个目标编辑一个“状态”,“注释”和“日期”列,然后单击一个按钮来更新主表。
主表和工作表都有一个我打算用于匹配的目标ID值。我希望能够遍历master数据库并查找“ update”表中是否有匹配的目标ID,并且是否需要从“ update”中的匹配行中更新master表中的三列。 ”表。我曾尝试在VBA中编写此循环,但我坚持使用正确的代码(我对VBA还是很陌生)。
这是我的代码:
Sub Button4_Click()
Dim i As Integer
Dim tbl As ListObject
Set tbl = Sheets("Master").ListObjects("MasterTable")
For i = 2 To tbl.Range.Rows.Count
If Sheets("Master").Cells(i, 1) = Sheets("Data Update").Cells(i, 1) Then
Range(Sheets("Data Update").Cells(i, 9), Sheets("Data Update").Cells(i, 11)).Copy
Range(Sheets("Master").Cells(i, 9), Sheets("Master").Cells(i, 11)).PasteSpecial xlPasteValues
ElseIf Sheets("Master").Cells(i + 1, 1) = Sheets("Data Update").Cells(i, 1) Then
Range(Sheets("Data Update").Cells(i, 9), Sheets("Data Update").Cells(i, 11)).Copy
Range(Sheets("Master").Cells(i, 9), Sheets("Master").Cells(i, 11)).PasteSpecial xlPasteValues
End If
Next i
End Sub
仅当“更新”表中的目标ID与“主”表中的目标ID在同一行时,该选项才有效。因此,如果目标ID#1在两个表的第1行中都将匹配,如果目标ID#2在两个表的第2行中都将匹配,依此类推。但是,如果目标ID不正确,则找不到目标ID。并且目标ID不会按顺序停止
答案 0 :(得分:0)
请参阅:
Sub UpdateTable()
Dim i As Integer
Dim tblMaster As ListObject, tblUpdate As ListObject
Dim valsReturned(1 To 2) As String
Dim valToFind As String
With ThisWorkbook
Set tblMaster = .Sheets("Master").ListObjects("MasterTable")
Set tblUpdate = .Sheets("Master").ListObjects("UpdateTable")
End With
With tblMaster.DataBodyRange
For i = 1 To .Rows.Count
'where is ID to find? please update as required
valToFind = .Cells(i, 1).Value
If CheckAndGetTableRow(tblUpdate, valToFind, valsReturned) Then
.Cells(i, 9).Value = valsReturned(1)
.Cells(i, 11).Value = valsReturned(2)
End If
Next i
End With
End Sub
Function CheckAndGetTableRow(ByRef tblUpdate As ListObject, ByVal valToFind As String, ByRef valsReturned() As String) As Boolean
Dim i As Integer, tRows As Integer
Dim success As Boolean
With tblUpdate.DataBodyRange
tRows = .Rows.Count
For i = 1 To tRows
'Please update if required, now ID is in first column
If .Cells(i, 1).Value = valToFind Then
'please update as required
valsReturned(1) = .Cells(i, 9).Value
valsReturned(2) = .Cells(i, 11).Value
success = True
Exit For
End If
Next
End With
CheckAndGetTableRow = success
End Function
谢谢