VBA根据值查找和更新行

我有一个主要的工作簿和多个孩子的工作簿,每个工作簿都在固定的位置,把工作logging保存为单独的行。 根据select哪个工作簿,将行从主工作簿复制到子工作簿。

然而,我坚持VBA编码(macros观forms),从而在每个孩子的工作簿,他们可以更新主。 我需要它根据分配给每件作品的唯一ID号find并更新主件中的工作行,并在子和主工作簿中出现在同一列(列D)中。

任何帮助或想法将不胜感激。

提前致谢

道歉。 请从我的示例子工作簿中看到下面的数据(对不起,我无法正确格式化),在下面,我必须将当前的VBA代码复制回主工作簿:

数据:

Complaint Type Raised by Status ID Billing Percy Completed 101 Billing Percy Completed 102 Metering John Pending 103 Reads John Pending 104 Reads Jack Pending 105 Billing Julie Untouched 106 Service Jack Completed 107 Metering Julie Untouched 108 Service Percy Pending 109 Payment Pete Pending 110 

VBA代码:

 Private Sub CommandButton21_Click() With Application .ScreenUpdating = False .EnableEvents = False End With Dim SourceRange As Range, DestRange As Range Set SourceRange = Sheets("Sheet1").Range("A2:D2") 'data source wb = ActiveWorkbook.Name Workbooks.Open "C:\Users\user\Desktop\Test.xlsm" 'path to Master Windows(wb).Activate 'Activate Child Workbook SourceRange.Cut 'define the range to copy 'Cut data from child workbook Windows("Test.xlsm").Activate 'Activate Master Sheets("Completed").Select 'Activate Sheet Workbooks("Test.xlsm").Sheets("Completed").Cells(Rows.Count, "A").End(xlUp).Offset(1).Paste 'Paste in Master Application.CutCopyMode = False 'Clear Clipboard End Sub 

下面的代码可以在你的每个孩子的工作簿中进行,我不确定这个ID在主工作簿中出现的位置,所以我只是假设D列与孩子相同,下面是未经testing的,并且基于孩子的D列与主机中的D列相匹配,它将更新列A,B和C.目前只对2000行进行更改(如果适用)。 🙂

 Dim fpath As String Dim owb As Workbook Dim Master As Worksheet Dim Slave As Worksheet 'the following declares both master and slave as worksheets fpath = "location of master workbook" Set owb = Application.Workbooks.Open(fpath) 'opens the file path Set Master = ThisWorkbook.Worksheets("name of sheet in child workbook") 'declares this workbook and sheet as "master" Set Slave = owb.Worksheets("name of sheet in master you are pasting to") 'declares the workbook and sheet you're copying to as "slave" For j = 1 To 2000 '(the master sheet) 'goes through each row from 1 to 2000 For i = 1 To 2000 '(the slave sheet) 'again does the same and the slave sheet If Trim(Master.Cells(j, 4).Value2) = vbNullString Then Exit For 'if the ID is blank it will exit and move on to the next row If Master.Cells(j, 4).Value = Slave.Cells(i, 4).Value Then 'the 4 represents column D, if cell in column D matches the cell in column D in the masterwork book then it will.. Slave.Cells(i, 1).Value = Master.Cells(j, 1).Value 'cell in column A child workbook equals cell in column A in master workbook Slave.Cells(i, 2).Value = Master.Cells(j, 2).Value Slave.Cells(i, 3).Value = Master.Cells(j, 3).Value 'same for B and C End If Next Next MsgBox ("Data Transfer Successful") With owb .Save .Close End With