我需要跳过vba按钮中的空单元格,然后在不为空时打开

时间:2019-02-07 11:30:09

标签: excel vba

我有一个按钮,每次单击链接时都会打开一个链接查询,但是有时查询中的字段为空,我需要我的代码继续执行并跳过空单元格,我该如何解决

我已经尝试过IsEmpty并且无法达到预期的结果。 VBA世界对我来说是一个新事物,因此,如果您发现任何愚蠢的错误或未通过优化方法警告我。下面的代码来自于我尝试跳过空白单元格之前的

Private Sub CommandButton1_Click()
    Dim SelecRng As Range

    Set SelecRng = ("F3:F44")

    Each Cell In SelecRng
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run (Cell)
    Next
End Sub

每当我尝试打开某些链接时,我都不想看到该错误

2 个答案:

答案 0 :(得分:1)

Tim Stack提供了一个很好的答案,但是我建议使用= vbNullString而不是= ""运行检查,并建议使用Cell.value2而不是Cell.value

在这个精确的示例中,这实际上并不重要,但在其他情况下,可能会很重要;所以最好现在就养成习惯。

那将是:

Private Sub CommandButton1_Click()
Dim SelecRng As Range

    Set SelecRng = ("F3:F44") 'I would add a reference to the WB and WS here. Now it always refers to the active WB & WS

    For Each Cell In SelecRng
        If Cell.Value2 <> vbNullString Then
            Set objShell = CreateObject("Wscript.Shell")
            objShell.Run (Cell.Value2)
        End If
    Next

End Sub

答案 1 :(得分:0)

Private Sub CommandButton1_Click()
Dim SelecRng As Range

Set SelecRng = ("F3:F44") 'I would add a reference to the WB and WS here. Now it always refers to the active WB & WS

For Each Cell In SelecRng
If not Cell.Value = "" Then
    Set objShell = CreateObject("Wscript.Shell")
    objShell.Run (Cell.Value)
End If
Next
End Sub