【问题标题】:Do sql request if there are no erros / Retrieve data如果没有错误,请执行 sql 请求/检索数据
【发布时间】:2018-06-27 09:18:41
【问题描述】:

在我的 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]")

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

【问题讨论】:

  • 如果您使用 T-SQL,您可以检查您的选择计数,如果为 0,则检查 RAISERROR
  • Dim count As Integer count = .Execute("select COUNT(*) from [values$S8:S8]") 类似的东西?
  • 没有那样你只会得到计数。您需要选择“smth”,然后检查 count(smth)。
  • 你有我的价值观的例子吗?

标签: sql excel vba


【解决方案1】:

如果您的想法是检查工作表是否存在,那就去做吧。忘记 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

【讨论】:

    【解决方案2】:

    另一个选择是非常小心地使用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
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 2022-01-27
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 2018-07-30
      • 2020-03-27
      相关资源
      最近更新 更多