为什么`Empty`在这个VBA代码中不起作用?
下面的代码应该检查一个单元格是否为空,如果是空的,则将B26的内容粘贴到该单元格中。 如果单元格不是空的,它将继续检查它下面的单元格。 我尝试使用IsEmpty
但没有奏效,所以我认为Excel是默认所有空单元格为0.所以我尝试使用Empty
(如下面的代码所示),但也不起作用。
Sub Part1_Component_1_Foam_Color() ' ' Transfers Component 1 Data if Foam or color ' ' Windows("Transfer Template.xlsm").Activate Range("B26").Select Selection.Copy Windows("Protected_JD_Form.xls").Activate If Range("B27:C27") = Empty Then Range("B27:C27").Select Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _ xlNone, SkipBlanks:=False, Transpose:=False Exit Sub ElseIf Range("B28:C28") = Empty Then Range("B28:C28").Select Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _ xlNone, SkipBlanks:=False, Transpose:=False Exit Sub ElseIf Range("B29:C29") = Empty Then Range("B29:C29").Select Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _ xlNone, SkipBlanks:=False, Transpose:=False Exit Sub ElseIf Range("B30:C30") = Empty Then Range("B30:C30").Select Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _ xlNone, SkipBlanks:=False, Transpose:=False Exit Sub End If Windows("Transfer Template.xlsm").Activate Range("A1").Select End Sub
您可以使用
If Application.WorksheetFunction.CountA(Range("B27:C27")) = 0 Then
代替
If Range("B27:C27") = Empty Then
顺便说一下,在粘贴数据之前不需要select范围。
这个代码
Range("B27:C27").Select Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _ xlNone, SkipBlanks:=False, Transpose:=False
可以换成
Range("B27:C27").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _ xlNone, SkipBlanks:=False, Transpose:=False
在VBA中使用Empty
或IsEmpty()
主要是为了查看一个variables是否已经被初始化,但是通常被误用来检查一个Range是否有值。
如果你想看看一个范围是否为“空”,那么使用:
If Range("B27").Value = vbNullString Then '// Do Something End If
如果你想检查有多个单元格的Range是空的,那么你可以使用一个COUNTA()
参数:
If [COUNTA(B27:C27)=0] Then '// Do Something End If
(或使用WorksheetFunction类的相同的东西…)
If WorksheetFunction.CountA(Range("B27:C27")) = 0 Then '// Do Something End If
试试IsEmpty
If IsEmpty(ws.Range("A1").Value) = True Then End if
你有没有尝试过
var = nz(YourValue,"")
然后检查
If var = "" Then 'moar code
或只是检查
If nz(YourValue,"") = "" Then 'moar code