我正在尝试使用VLOOKUP函数从另一个文件中检索数据,但这只会发生,具体取决于第3列(C)中是否有任何2项数据
“PO材料”或 “PO劳工”
Sub MakeFormulas()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim X As Long
'What are the names of our worksheets?
Set sourceSheet = Worksheets("Sheet1")
Set outputSheet = Worksheets("Sheet2")
'Determine last row of source
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
'Determine last row in col C
OutputLastRow = .Cells(.Rows.Count, "E").End(xlUp).Row
For X = 5 To OutputLastRow
If InStr(1, .Range("C" & X), "PO Materials") > 0 Then
'Apply our formula
.Range("Q2:Q" & OutputLastRow).Formula = _
"=VLOOKUP(E2,'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"
End If
Next
End With
End Sub
代码正在运作;但是,如果单元格为空或在C列中包含任何值,则给出#N / A,这意味着它不识别If语句。如果该列不包含“PO材料”或“PO人工”,我希望它跳到范围内的下一个单元格
提前感谢您提供的任何帮助。
答案 0 :(得分:1)
生成VLOOKUP的代码每次都会将该公式应用于列中的每个单元格。也就是说,每当If
条件找到" PO材料"时,它就会将VLOOUKP应用于Q2和E列最后一行之间的每个单元格。
我认为这就是你想要的:
.Range("Q" & X).Formula = _
"=VLOOKUP(E" & X & ",'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"
或者,它可以在电子表格中完成:
=IF(ISERROR(FIND("PO Materials",C6)),"",VLOOKUP(E6,Sheet1!$A$2:$B$6,2,0))
答案 1 :(得分:0)
最终准则以供将来参考
Sub MakeFormulas()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim X As Long
'What are the names of our worksheets?
Set sourceSheet = Worksheets("Sheet1")
Set outputSheet = Worksheets("Sheet2")
'Determine last row of source
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
'Determine last row in col C
OutputLastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
For X = 2 To OutputLastRow
If InStr(1, .Range("C" & X), "PO Materials") + InStr(1, .Range("C" & X), "PO Labor") > 0 Then
'Apply our formula
.Range("Q" & X).Formula = _
"=VLOOKUP(E" & X & ",'" & sourceSheet.Name & "'!$A$2:$B$" & SourceLastRow & ",2,0)"
End If
Next
End With
End Sub