我有兩個工作簿:vba複製另一個工作簿中的相應值?
規劃
Column K Column AG
123 £100
246 £20
555 £80
主
Column D Column R
123 £100
246 £20
555 £80
我想要的值從計劃複製,欄AG到R列(主)在我的項目號碼D列(主)與K列(Planner)匹配。
我的下面的代碼沒有產生任何錯誤,並且沒有產生任何結果 - 儘管它們有幾個匹配。
請有人能告訴我我要去哪裏嗎?
爲了避免疑惑,我的工作手冊確實可以打開,所以查找文件。
代碼:
Sub PlannerOpen()
'Set Variables
Dim wb2 As Workbook
Dim i As Long
Dim j As Long
Dim lastRow As Long
Dim app As New Excel.Application
'Find Planner
If Len(FindDepotMemo) Then
'If Found Then Set Planner Reference.
app.Visible = False 'Visible is False by default, so this isn't necessary
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Set wb2 = Workbooks.Open(FindDepotMemo, ReadOnly:=True, UpdateLinks:=False)
'If We have our planner lets continue...
'With my workbook
With wb2.Worksheets(1)
lastRow = .Cells(.Rows.Count, "K").End(xlUp).Row
'Lets begin our data merge
j = 2
For i = 2 To lastRow
'If data meets criteria
'Check Planner For Turnover
If ThisWorkbook.Worksheets("Data").Range("D" & j).Value = .Range("K" & i).Value Then ' check if Item number matches
ThisWorkbook.Worksheets("Data").Range("R" & j).Value = .Range("AG" & i).Value
j = j + 1
End If
'Continue until all results found
Next i
End With
'All Done, Let's tidy up
'Close Workbooks
'wb2.Close SaveChanges:=False
'app.Quit
'Set app = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.EnableEvents = True
End If
End Sub
Function FindDepotMemo() As String
Dim Path As String
Dim FindFirstFile As String
Path = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\" & "8." & " " & Year(Date) & "\"
FindFirstFile = Dir$(Path & "*.xlsx")
While (FindFirstFile <> "")
If InStr(FindFirstFile, "Planner") > 0 Then
FindDepotMemo = Path & FindFirstFile
Exit Function
End If
FindFirstFile = Dir
Wend
End Function
這看起來像在工作['VLOOKUP()']( https://support.office.com/en-gb/article/VLOOKUP-function-0bbc8083-26fe-4963-8ab8-93a18ad188a1)功能。 – Phylogenesis
@Phylogenesis如果可能,我想保留它vba – user7415328
只有在i = 2和j = 2的情況下,您的代碼纔會查看並且遞增,因此vba只檢查1個值,然後轉到下一個值。 ..但你想要的是1的價值檢查範圍內,如果發現返回價值......正確...你可能需要另一個循環獲得 –