excel 我已经试着修改这个代码很多次了,它就是不起作用

wvmv3b1j  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(167)

我已经尝试了这个vba代码,但它只是不工作,我无法看到错误。这是代码

Sub RetrieveData()
    Dim i As Long
    Dim targetWorkbook As Workbook
    Dim targetWorksheet As Worksheet
    Dim targetFilePath As String
    Dim targetFileName As String
    
    ' Set the target file path and name
    targetFilePath = "\\kcjmserver\E\Data\Overseas Projects\Honilac Nutrition Limited\2023\Amazon reconciliation\D05 May 2023\Vlookup"
    targetFileName = "InventoryItems-20230605.xlsx"
    
    ' Open the target workbook
    Set targetWorkbook = Workbooks.Open(targetFilePath & "\" & targetFileName)
    
    ' Set the target worksheet
    Set targetWorksheet = targetWorkbook.Worksheets("Sheet1") ' Replace "Sheet1" with the actual sheet name
    
    ' Loop through the data in Sheet1
    For i = 2 To 26
        ' Perform the VLOOKUP
        Worksheets("Sheet1").Cells(i, 10).Value = Application.VLookup(Worksheets("Sheet1").Cells(i, 6).Value, targetWorksheet.Range("A:M"), 9, False)
        Worksheets("Sheet1").Cells(i, 7).Value = Application.VLookup(Worksheets("Sheet1").Cells(i, 6).Value, targetWorksheet.Range("A:M"), 3, False)
    Next i
    
    ' Close the target workbook
    targetWorkbook.Close SaveChanges:=False
    
    ' Release the memory
    Set targetWorksheet = Nothing
    Set targetWorkbook = Nothing
End Sub

我已经尝试了替代代码,似乎没有工作,我想从另一个工作簿中获取数据

kkbh8khc

kkbh8khc1#

ThisWorkbook添加到对Worksheets("Sheet1")的引用。

Option Explicit

Sub RetrieveData()

    Dim i As Long
    Dim wbLookUp As Workbook, rngLookUp As Range
    
    ' Set the look-up file path and name
    Const LookUpPath = "\\kcjmserver\E\Data\Overseas Projects\Honilac Nutrition Limited\2023\Amazon reconciliation\D05 May 2023\Vlookup"
    Const LookUpName = "InventoryItems-20230605.xlsx"
    
    ' Open the look-up workbook
    Set wbLookUp = Workbooks.Open(LookUpPath & "\" & LookUpName)
    
    ' Set the look-up range
    With wbLookUp
        Set rngLookUp = .Sheets("Sheet1").Range("A:M")
    End With
    
    ' Loop through the data in Sheet1
    With ThisWorkbook.Sheets("Sheet1")
        For i = 2 To 26
            ' Perform the VLOOKUP
            .Cells(i, 7).Value = Application.VLookup(.Cells(i, 6).Value, rngLookUp, 3, False)
            .Cells(i, 10).Value = Application.VLookup(.Cells(i, 6).Value, rngLookUp, 9, False)
        Next i
    End With
    
    ' Close the look-up workbook
    wbLookUp.Close SaveChanges:=False
    
End Sub

相关问题