Vba:如何使用“如果不为空”
您可以在 VBA 中使用Not IsEmpty来检查单元格是否不为空。
以下是如何在宏中使用此语法的示例:
Sub IfNotBlank()
Dim i As Integer
For i = 2 To 13
If Not IsEmpty(Range(" A " & i)) Then
Result = “ Cell is Not Empty ”
Else
Result = “ Cell is Empty ”
End If
Range(" B " & i) = Result
Next i
End Sub
此特定示例检查范围A2:A13中的每个单元格是否不为空,然后为范围B2:B13中的每个匹配单元格打印“单元格不为空”或“单元格为空”。
以下示例展示了如何在实践中使用此语法。
示例:如何在 VBA 中使用“如果不为空”
假设我们在 Excel 中有以下篮球队名称列表:
假设我们要检查区域A2:A13中的每个单元格是否不为空,然后将结果显示在区域B2:B8中的相应单元格中。
我们可以创建以下宏来执行此操作:
Sub IfNotBlank()
Dim i As Integer
For i = 2 To 13
If Not IsEmpty(Range(" A " & i)) Then
Result = “ Cell is Not Empty ”
Else
Result = “ Cell is Empty ”
End If
Range(" B " & i) = Result
Next i
End Sub
当我们运行这个宏时,我们会收到以下输出:
B 列告诉我们 A 列中每个相应的单元格是否为空。
如果 A 列中的值不为空,您还可以使用以下宏简单地在 B 列中返回团队名称本身:
Sub IfNotBlank()
Dim i As Integer
For i = 2 To 13
If Not IsEmpty(Range(" A " & i)) Then
Result = Range(" A " & i).Value
Else
Result = " Empty "
End If
Range(" B " & i) = Result
Next i
End Sub
当我们运行这个宏时,我们会收到以下输出:
如果单元格不为空,B 列现在会返回 A 列中的团队名称。
注意:您可以在此处找到 VBA IsEmpty方法的完整文档。
其他资源
以下教程说明如何在 VBA 中执行其他常见任务: