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

我有代码,把公式放到区域,它工作正常:

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对象引用混合起来即可。
要引用单个单元格,您有两个解决scheme:

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

要么

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