带公式的循环

时间:2018-09-07 17:31:20

标签: vba excel-vba for-loop

我有下面的代码想要在循环中使用。但是,我希望此循环在C5列和D5列的所有单元上运行,而不是CD }和C5

总而言之,我希望D5C5列中的每个单元格都替换D5C。请协助。

D

1 个答案:

答案 0 :(得分:2)

认为这可以满足您的需求。它将从C的第1行到最后一行。请注意,无需VBA即可完成所有操作。

Sub x()

Dim i As Long, Valuex As Boolean, Valuex1 As Boolean

For i = 1 To Range("C" & Rows.Count).End(xlUp).Row
    Valuex = Evaluate("=IsNumber(Value(Mid(C" & i & ", 2, 1)))")
    MsgBox (Valuex)
    Valuex1 = Evaluate("=Left(Trim(C" & i & "), 1) = ""R""")
    MsgBox (Valuex1)
    If Valuex1 And Valuex Then
        Range("D" & i).Formula = "=VLOOKUP(C" & i & ",[old.xls]Sheet1!$D:$V,19,0)"
        MsgBox ("if")
    Else
        Range("D" & i).Formula = "=VLOOKUP(C" & i & ",[old.xls]Sheet1!$E:$V,18,0)"
        MsgBox ("else")
    End If
Next i

End Sub

我认为您可以完全避免循环

Sub xx()

Dim i As Long

i = Range("C" & Rows.Count).End(xlUp).Row

With Range("D1:D" & i)
    .Formula = "=IF(AND(ISNUMBER(VALUE(MID(C1, 2, 1))),LEFT(TRIM(C1), 1) = ""R""),VLOOKUP(C1,Sheet1!$D:$V,19,0),VLOOKUP(C1,Sheet1!$E:$V,18,0))"
    .Value = .Value
End With

End Sub