你目前的代碼不會做任何接近你想要的。試試下面的代碼,看看它是否適合你。我試着添加一些註釋來解釋代碼在做什麼。確保在代碼中更改工作簿和工作表名稱以匹配您的實際書籍。
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文件,它可以包含多個工作表(文件底部的「選項卡」)。你是指哪一個? –