以下代码在不同工作簿之间进行复制和粘贴。我不确定为什么没有“Source.Activate”和“Master.Activate”系列就行不通?换句话说,为什么要激活工作簿,尽管它们在开始时被声明和设置?
Dim Source As Worksheet
Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")
Dim Master As Worksheet
Set Master = Workbooks("Master.xlsm").Worksheets(Sheets.Count)
Source.Activate '???
For Each cell In Source.Columns("M").Cells
If cell <> "" Then
Master.Activate '???
For Each cell2 In Master.Columns("J").Cells
If cell2 <> "" Then
If cell = cell2 Then
cell2.Offset(0, 9).Value = cell.Offset(0, -2).Value
cell2.Offset(0, 8).Value = cell.Offset(0, -8).Value
End If
End If
Next cell2
End If
Next cell
提前致谢, 鲍尔泰克
答案 0 :(得分:1)
源和目标工作簿都不能处于活动状态以执行复制/粘贴。例如:
Sub Macro1()
Dim b1 As Workbook, b2 As Workbook
Dim r1 As Range, r2 As Range
Workbooks.Open Filename:="C:\TestFolder\1\1.xlsx"
Set b1 = ActiveWorkbook
Set r1 = b1.Sheets("Sheet1").Range("A1")
Workbooks.Open Filename:="C:\TestFolder\1\2.xlsx"
Set b2 = ActiveWorkbook
Set r2 = b1.Sheets("Sheet1").Range("A1")
ThisWorkbook.Activate
r1.Copy r2
End Sub
答案 1 :(得分:1)
您根本不需要激活活动或与活动工作簿有关。 但是您确实需要使用匹配或查找而不是循环遍历主文件中的每个单元格。
Not IsError
是跳过非匹配,因为匹配在找不到匹配项时会抛出错误。 Match函数返回它找到的第一个匹配的行号。
另一件事.Worksheets(Sheets.Count)
返回工作簿中的最后一个工作表,为什么不将它设置为像source这样的工作表名称?
Dim Source As Worksheet
Dim Master As Worksheet
Set Source = Workbooks("Source.xlsx").Worksheets("Settlements")
Set Master = Workbooks("Master.xlsm").Worksheets(Sheets.Count)
For Each c In Source.Columns("M").Cells
If c <> "" Then
If Not Application.WorksheetFunction.IsError(Application.Match(c, Master.Columns("J"), 0)) Then
crow = Application.Match(c, Master.Columns("J"), 0)
Master.Range("J" & crow).Offset(0, 9).Value = c.Offset(0, -2).Value
Master.Range("J" & crow).Offset(0, 8).Value = c.Offset(0, -8).Value
End If
'End If
'Next cell2
End If
Next c