【发布时间】:2020-08-13 01:05:11
【问题描述】:
想要从 workbook1 的 sheet1 增量比较值与 workbook2 的 sheet1 的值,如果值匹配,则将工作表 1 的粘贴数据复制到工作表 2,WB1S1 包含三列要比较的两个值和要复制的值,WB2S1 包含两列两者都与 WB1S1 的前两列进行比较,如果值匹配,则将 WB1S1 第三列的值复制到 WB2S1,该值可以是任何方式,例如 WB1S1 的 A1:B1 匹配 WB2S1 的 A2:B2 然后,将 WB1S1 的 C1 复制到 C2 的WB2S1
这里是代码
Sub Compare()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim myTemp As Workbook, myMain As Workbook
Dim temppath As String, mainfile As String
Dim wsTempwsMain As Worksheet, wsMain As Worksheet
temppath = "workbook1.xlsx"
mainfile = "workbook2.xlsx"
Set myTemp = Workbooks.Open(filename:=temppath)
Set wsTemp = myTemp.Sheets("Sheet1")
Set myMain = Workbooks.Open(filename:=mainfile)
Set wsMain = myMain.Sheets("Sheet1")
wsTemp.Activate
wsMain.Activate
Dim TemplastRow As Long, MainlastRow As Long
Dim MainLastColumn As Long
TemplastRow = wsTemp.Range("B2").End(xlDown).Row
MainlastRow = wsMain.Range("B4").End(xlDown).Row
With wsMain.UsedRange
MainLastColumn = .Columns(.Columns.Count).Column
End With
For i = 2 To TemplastRow
For j = 4 To MainlastRow
If myTemp.wsTemp.Range(Cells(i, 2), Cells(i, 2)).Value = myMain.wsMain.Range(Cells(j, 2), Cells(j, 2)).Value And myTemp.wsTemp.Range(Cells(i, 3), Cells(i, 3)).Value = myMain.wsMain.Range(Cells(j, 3), Cells(j, 3)).Value Then
myTemp.wsTemp.Range(Cells(i, 4), Cells(i, 8)).Select
Selection.Copy
myMain.wsMain.Range(Cells(j, MainLastColumn), Cells(j, MainLastColumn)).Select
wsMain.Paste
End If
Next j
Next i
myWb.Save
myWb.Close SaveChanges:=True
End Sub
【问题讨论】:
-
请注意,
Dim temppath, mainfile As String仅将mainfile声明为String,而将temppath声明为Variant。在 VBA 中,您需要为 每个 变量指定一个类型:Dim temppath As String, mainfile As String否则默认为Variant。其他变量声明也是如此。 -
最好避免激活和选择。只需使两个单元格相等即可避免复制和粘贴。
-
你不能用
VLookUp来做这个吗? -
@DarrellH 你能详细说明一下吗,它会起作用吗