你目前的代码不会做任何接近你想要的。试试下面的代码,看看它是否适合你。我试着添加一些注释来解释代码在做什么。确保在代码中更改工作簿和工作表名称以匹配您的实际书籍。
Sub RunMe()
Dim wbk1 As Workbook, wbk2 As Workbook, wbk3 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
Dim lRow1 As Long, lCol1 As Long, lRow3 As Long, x As Long
Dim myValue As String
Dim Found As Range
Set wbk1 = Workbooks("Workbook_1.xlsm") 'Be sure to change these to your actual workbook names
Set ws1 = wbk1.Worksheets("Sheet1") 'Be sure to change these to your actual worksheet names
Set wbk2 = Workbooks("Workbook_2.xlsm")
Set ws2 = wbk2.Worksheets("Sheet1")
Set wbk3 = Workbooks("Workbook_3.xlsm")
Set ws3 = wbk3.Worksheets("Sheet1")
'Using a with block means we don't have to define any range coming from book1. ws1.Range("A2") is the same as .Range("A2")
With ws1
'Find last row in ws1 Col A
lRow1 = .Range("A" & .Rows.Count).End(xlUp).Row
'Find last column in ws1
lCol1 = .Cells.Find(What:="*", _
After:=.Cells(1, 1), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
'Start loop to search through all values in column A
For x = 2 To lRow1
myValue = .Cells(x, 1).Value
'Look for value in Workbook2 column A
Set Found = ws2.Cells.Find(What:=myValue, _
After:=ws2.Cells(1, 1), _
LookIn:=xlFormulas, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
'If Found is not nothing then do something
If Not Found Is Nothing Then
'Find last row in ws3 Col A
lRow3 = ws3.Range("A" & .Rows.Count).End(xlUp).Row
'Instead of using .copy saying "This Range = That Range" is much faster
ws3.Range(ws3.Cells(lRow3 + 1, 1), ws3.Cells(lRow3 + 1, lCol1)).Value = .Range(.Cells(x, 1), .Cells(x, lCol1)).Value
End If
Next x
End With
End Sub
你的代码在哪里给出一个错误,出现什么错误?首先你说你想循环访问列A,但你一直引用列E. – BerticusMaximus
嗨,没有错误,当我运行代码时,它需要几分钟的时间运行,然后停止并没有发生,没有任何副本或任何东西workbook_3 - 关于Col A&E它正确地输入为A,但是我在这里输入了我发现编辑的原始代码,以便轻松查看它是我的错误还是代码本身。 – user3103193
您指的是代码中的“表格”,但是您会谈论“工作簿”?工作簿是一个Excel文件,它可以包含多个工作表(文件底部的“选项卡”)。你是指哪一个? –