当“D”列中的相应单元格为空时,我试图将vlookup公式添加到多个列(E:I)。例如,当单元格D113和向下是空白时,我想将“= VLOOKUP(A2,Sheet4!$ A:$ L,5,False)”添加到单元格E113:然后向下然后重复为列G,H,I,等等
但是我现在的代码如下所示,将vlookup添加到E&列中的所有单元格中。 lastrow,覆盖E113以上的现有数据。代码如下:
Sub PrevInactives()
Dim ws As Worksheet
Dim lastrow As Long
lastrow = Range("A2").End(xlDown).Row
For Each Cell In Sheets(1).Range("D2:D" & lastrow)
Select Case Cell.Value
Case ""
If Cell.Offset(1, 0) = "" Then
Range("E2:E" & lastrow).Formula = "=VLOOKUP(A2,Sheet3!$A:$L,5,FALSE)"
End If
End Select
Next Cell
End Sub
有没有人能解决我的困境?
谢谢,
杰森
编辑,9/26/17:下面是我添加的更新代码,但是当我运行此宏时,没有任何反应。
Sub PrevInactives()
Dim r As Long
For r = 2 To lastrow
lastrow = Range("A2").End(xlDown).Row
If IsEmpty(Cells(r, 4).Value) And Not IsEmpty(Cells(r - 1, 4).Value) Then
Range(Cells(r, 5), Cells(r, 9)).Formula = "=VLOOKUP($A2" & r & ",Sheet4!$A:$L,False)"
End If
Next r
End Sub
答案 0 :(得分:0)
如果我理解正确,你想要在你的循环中包含以下内容:
If IsEmpty(Cells(r,4).Value) AND Not IsEmpty(Cells(r-1,4).Value) Then
'Insert vlookup stuffs
End If
不是使用For Each作为循环,而是使用上面的例子将r = 2循环到LR:
Dim r as Long
For r = 2 to lastrow
If IsEmpty(Cells(r,4).Value) AND Not IsEmpty(Cells(r-1,4).Value) Then
Range(Cells(r,5),Cells(r,9)).Formula= "=VLOOKUP($A" & r & ",Sheet3!$A:$L,5,FALSE)"
End If
Next r
基本上,问题在于你正在使用:
Range("E2:E" & lastrow).Formula = "=VLOOKUP(A2,Sheet3!$A:$L,5,FALSE)"
当你想要Cell.Formula ="&#34 ;;如果情况确实如此,那么你要将公式添加到所有这些单元格中。
编辑,20170926:
修复代码:
Sub PrevInactives()
Dim r As Long, lastrow as Long
lastrow = Range("A2").End(xlDown).Row 'Need to define before looping
'You could use lastrow = Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To lastrow
If IsEmpty(Cells(r, 4).Value) And Not IsEmpty(Cells(r - 1, 4).Value) Then
Range(Cells(r, 5), Cells(r, 9)).Formula = "=VLOOKUP($A" & r & ",Sheet4!$A:$L,False)" 'You had in A2&r, so it would be A22, A23, ..., A2&LR
End If
Next r
End Sub