繁体   English   中英

VBA-如果单元格为空,则跳过子

[英]VBA - if cell is empty then skip the sub

我有代码,将公式放到区域中,并且效果很好:

Private Sub Jeeves_account2_C()

Dim lastrow As Long
Dim rng As Range, C As Range

With Worksheets("Crd_Headers") ' <-- here should be the Sheet's name
    lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row ' last row in column B
    Set rng = .Range("C2:C" & lastrow) ' set the dynamic range to be searched

    ' loop through all cells in column B
    For Each C In rng
        If Not IsEmpty(C.Value) Then
            C.Offset(, -1).Formula = "=IFERROR(VLOOKUP(RC[2],Jeeves_Cust_list!C[-1]:C[1],3,0),RC[2])" ' use offset to put the formula in column "P"
        End If
    Next C
End With

End Sub

但我想补充一下条件,如果工作表Crd_Headers上的单元格C2为空,则跳过整个子项:

If Worksheets("Crd_Headers").Cells("C2") = "" Then
    Exit Sub
End If

因此,代码如下所示:

Private Sub Jeeves_account2_C()

If Worksheets("Crd_Headers").Cells("C2") = "" Then
    Exit Sub
End If

Dim lastrow As Long
Dim rng As Range, C As Range

With Worksheets("Crd_Headers") ' <-- here should be the Sheet's name
    lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row ' last row in column B
    Set rng = .Range("C2:C" & lastrow) ' set the dynamic range to be searched

    ' loop through all cells in column B
    For Each C In rng
        If Not IsEmpty(C.Value) Then
            C.Offset(, -1).Formula = "=IFERROR(VLOOKUP(RC[2],Jeeves_Cust_list!C[-1]:C[1],3,0),RC[2])" ' use offset to put the formula in column "P"
        End If
    Next C
End With

End Sub

但是它给我错误消息无效的过程调用或参数

你能告诉我,我做错了什么?

谢谢!

您只需将CellsRange对象引用混合在一起。
要引用单个单元格,您有两种解决方案:

If Worksheets("Crd_Headers").Range("C2") = "" Then

要么

If Worksheets("Crd_Headers").Cells(2, "C") = "" Then

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM