0

下面的 VBA 代码应该 1)在另一个文件中选择一系列单元格 2)在活动文件中插入一个新列 3)当它遍历 C 列中的每一行时,它会在单元格范围内查找相应的值在来自 #1 的另一个文件中 4) 在它正在查找的文件旁边的列中输入值

但是,它只是不起作用,我不确定作为新手有什么问题..请帮忙。

Sub Translate()
Dim PartName As String
Dim CellName As String
Dim PartNameList As Range
Dim i As Integer

Set PartNameList = Workbooks("C:\Users\" "\Desktop\Part name translation.xlsx").Worksheets("Reference").Range("A1:B2000")

Worksheets("Initial").Columns("D").Insert
For i = 2 To Range("C2:C3000").Count
    If IsEmpty("C" & i) = True Then Exit For
    PartName = WorksheetFunction.VLookup(Range("C" & i), PartNameList, 2, False)
    Range("C" & i).Value = PartName
Next i

End Sub
4

1 回答 1

1

您没有传递有效的工作簿名称:

 Set PartNameList = Workbooks( _
    "C:\Users\" "\Desktop\Part name translation.xlsx"). _
    Worksheets("Reference").Range("A1:B2000")

看来您缺少一个环境变量,这应该可以解决它:

dim uName as String: uName = Environ("Username")
Set PartNameList = Workbooks( _
    "C:\Users\" & uName & "\Desktop\Part name translation.xlsx"). _
    Worksheets("Reference").Range("A1:B2000")

但是,如果工作簿已经打开,您不需要完全限定它,您可以使用文件名:

Set PartNameList = _
   Workbooks("Part name Translation.xlsx").Worksheets("Reference").Range("A1:B2000")

最后,如果工作簿未打开,我认为您需要首先打开它:

dim uName as String: uName = Environ("Username")
dim wbPartName as Workbook
Set wbPartName = Workbooks.Open( _
    "C:\Users\" & uName & "\Desktop\Part name translation.xlsx")
Set partNameList = wbPartName.Worksheets("Reference").Range("A1:B2000")
于 2013-05-22T21:15:44.003 回答