寻找一种方法做一个IF小区说(这个)然后VLOOKUP在这里,IF小区说(thiselse)然后VLOOKUP不同的区域。
这可能是一个非常明显的方法,到目前为止:
很简单,但不工作
Sub categoryVLOOKUP()
'IF col D says STAR then enter VLOOKUP formula into column K
'IF col D says SUN then enter other VLOOKUP formula into column K
Dim lRow As Long, lCol As Long
Dim lRow2 As Long
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("STARSUN")
For lRow = 2 To LastRow
If sht.Cells(lRow, 4) = "SUN" Then
sht.Cells(lRow, 10).Formula = _
"=VLOOKUP(A3&G3,OF_MOON!A:D, 4,0)"
Else
End If
If sht.Cells(lRow, 4) = "STAR" Then
sht.Cells(lRow, 10).Formula = _
"=VLOOKUP(A3&G3,OFWORLD!A:D, 4,0)"
Else
End If
Next lRow
End Sub
如果它正在获得多个单元格的公式,那么我会推荐R1C1格式:
Sub categoryVLOOKUP()
'IF col D says STAR then enter VLOOKUP formula into column K
'IF col D says SUN then enter other VLOOKUP formula into column K
Dim lRow As Long, lCol As Long
Dim lRow2 As Long
Dim sht As Worksheet
Dim LastRow as long
LastRow = Cells(Rows.Count, "D").End(xlUp).Row
Set sht = ThisWorkbook.Worksheets("STARSUN")
For lRow = 2 To LastRow
If sht.Cells(lRow, 4) = "SUN" Then
sht.Cells(lRow, 10).FormulaR1C1 = _
"=VLOOKUP(R[1]C[-8]&R[1]C[-1],OF_MOON!RC:RC[3], 4,0)"
ElseIf
If sht.Cells(lRow, 4) = "STAR" Then
sht.Cells(lRow, 10).FormulaR1C1 = _
"=VLOOKUP(R[1]C[-8]&R[1]C[-1],OFWORLD!RC:RC[3], 4,0)"
End If
Next lRow
End Sub
我认为这一系列思路应该让你开始。请记住,R1C1必须参考公式将进入的活动单元格。我可能需要检查引用新表格的规则但是,这应该让你在正确的行上:)希望它有帮助
编辑:此外,我相信你确实需要设置我已添加到代码中的LastRow
Dim LastRow as long
和
LastRow = Cells(Rows.Count, "D").End(xlUp).Row
看起来你缺少LastRow
的定义和价值。
在模块的开头使用option explicit
来强制执行变量声明。或者只是工具 - >选项 - >检查需要变量声明。它将自动完成。
另外我不明白为什么你甚至会使用VBA。你不能只使用配方
=IF(cell="SUN",1st vlookup, if(cell="STAR", 2nd vlookup,NA())
另外我建议使用INDEX + MATCH而不是VLOOKUP。
第三个“也”:你正在硬编码你将要注意的关键:A3&G3
。因此,您将从您的操作中获得最多3个值:无论与OF_MOON表单或OFWORLD表单或A3&G3
中的#N/A
相关联。
获得结果的另一种方法如下
Sub categoryVLOOKUP()
Dim lRow As Long, lCol As Long
Dim lRow2 As Long
Dim sht As Worksheet
LastRow = Range("D" & Rows.Count).End(xlUp).Row
Set sht = ThisWorkbook.Worksheets("STARSUN")
For lRow = 2 To LastRow
If sht.Cells(lRow, 4) = "SUN" Then
Range("K" & lRow).Value = Application.WorksheetFunction.VLookup(Range("A" & lRow) & Range("G" & lRow), Worksheets("OF_MOON").Range("A:D"), 4, 0)
ElseIf sht.Cells(lRow, 4) = "STAR" Then
Range("K" & lRow).Value = Application.WorksheetFunction.VLookup(Range("A" & lRow) & Range("G" & lRow), Worksheets("OF_MOON").Range("A:D"), 4, 0)
End If
Next lRow
End Sub