寻找一种方法来做一个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
答案 0 :(得分:1)
如果要获得多个单元格的公式,那么我建议使用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
答案 1 :(得分:0)
您似乎缺少LastRow
的定义和价值。
在模块的开头使用option explicit
来强制执行变量声明。或者只是工具 - >选项 - >检查需要变量声明。它将自动完成。
另外,我不明白为什么你甚至会使用VBA。你不能只使用公式
=IF(cell="SUN",1st vlookup, if(cell="STAR", 2nd vlookup,NA())
另外我建议使用INDEX + MATCH而不是VLOOKUP。
还有第3个“也”:你正在硬编码你要查找的密钥:A3&G3
。因此,您将从您的操作中获得最多3个值:与OF_MOON表单或OFWORLD表单中的A3&G3
或#N/A
相关联的任何值。
答案 2 :(得分:0)
获得结果的另一种方法如下
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