如果没有错误/执行数据,请执行sql请求

时间:2018-06-27 09:18:42

标签: sql excel vba

在我的Excel VBA代码中,我打开了与其他工作簿的连接。

  With CreateObject("ADODB.Connection")
        .CommandTimeout = 500
        .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
        & path & ";" & "Extended Properties=""Excel 12.0;HDR=NO;Readonly=true"";"
    .Open

我想做这样的一行:

ThisWorkbook.Worksheets("Test").Range("H306:307").CopyFromRecordset .Execute("select * from [values$S8:S8]")

但是,表单“值”可能不存在,这就是为什么我只想在没有错误或“值”存在的情况下才执行此行,但我不知道该怎么做

2 个答案:

答案 0 :(得分:0)

如果您的想法是检查工作表是否存在,请执行此操作。忘了SQL,它是不相关的:

Public Function worksheetExists(wb As Workbook, sh As Worksheet) As Boolean    
    worksheetExists = IsError(wb.sh.Range("A1"))    
End Function

如果要将文件的开头放在函数中,则:

Public Function worksheetExists(path As String, sh As Worksheet) As Boolean

    On Error GoTo worksheetExists_Error

    Dim wb As Workbook
    Set wb = Workbooks.Open(path)
    worksheetExists = IsError(wb.sh.Range("A1"))

    wb.Close False

    On Error GoTo 0
    Exit Function

worksheetExists_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") "

End Function

答案 1 :(得分:0)

另一种选择是非常小心地使用On Error Resume Next,因为它会忽略任何错误。但是,您可以将其放在一行上,然后放入On Error GoTo 0,这将停止操作。最后,在为新工作表分配值之前,请检查是否rs is not Nothing

Public Sub TestMe()

    Dim path As String: path = "C:\Source.xlsx"
    Dim rs As Object

    With CreateObject("ADODB.Connection")
        .CommandTimeout = 500
        .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
                    & path & ";" & _
                    "Extended Properties=""Excel 12.0;HDR=NO;Readonly=true"";"
        .Open

        On Error Resume Next
        Set rs = .Execute("SELECT * FROM [Sheet12$A1:B4]")
        On Error GoTo 0
    End With

    If Not rs Is Nothing Then
        With ThisWorkbook.Worksheets(1).Range("A1")
            .CopyFromRecordset rs
        End With
    End If

End Sub