개체를 할당 할 때 VBA 오류 91의 원인은 무엇일까요

Nov 16 2020

Excel에 Access 데이터베이스의 데이터를 쿼리하는 매크로가 있습니다. 저와 잘 작동합니다. 몇 명의 동료와 파일을 공유했는데 두 명은 "91 Object variable 또는 With block variable not set"오류가 계속 발생합니다.

디버깅은이 줄이 범인임을 나타냅니다.

Set rs = objAccess.CurrentProject.Connection.Execute(SQL)

공유 할 수있는 통찰력을 감사하십시오. 아래 관련 코드.

Sub RefreshData()
On Error GoTo SubError
    Const DbLoc As String = "path to .accdb"
    Dim objAccess As Object 
    Dim rs As Object 
    Dim xlBook As Workbook
    Dim xlSheet As Worksheet
    Dim recCount As Long
    Dim SQL As String
    Const cstrPwd As String = "foo"
 
    'Setup references to workbook and sheet
    Set xlBook = ActiveWorkbook
    
    If xlBook Is Nothing Then
        MsgBox "xlBook not found"
    End If
    
    Set xlSheet = xlBook.Worksheets(2)
    
    If xlSheet Is Nothing Then
        MsgBox "xlSheet not found"
    End If
    
    xlSheet.Range("A5:BA99000").ClearContents
   
    'Communicate with the user
    Application.StatusBar = "Connecting to an external database..."
    Application.Cursor = xlWait
 
    ' connect to the Access database
    On Error Resume Next
    Set objAccess = GetObject(, "Access.Application")
    If Err.Number <> 0 Then
        Set objAccess = CreateObject("Access.Application")
    End If
    On Error GoTo SubError
    objAccess.Visible = False
    objAccess.OpenCurrentDatabase DbLoc, , cstrPwd

    SQL = "SELECT * FROM [name of predefined select query in Access]"
    
    'Execute our query and populate the recordset
    Set rs = objAccess.CurrentProject.Connection.Execute(SQL) ' The culprit :)
 
    If rs Is Nothing Then
        MsgBox "rs not found. SQL=" & SQL
    End If
 
    'Copy recordset to spreadsheet
    Application.StatusBar = "Writing to spreadsheet..."
    If rs.RecordCount = 0 Then
        MsgBox "No data retrieved from database", vbInformation + vbOKOnly, "No Data"
        GoTo SubExit
    Else
        rs.MoveLast
        recCount = rs.RecordCount
        rs.MoveFirst
    End If
   
    xlSheet.Range("A5").CopyFromRecordset rs
    Application.StatusBar = "Update complete"

 
SubExit:
On Error Resume Next
    Application.Cursor = xlDefault
    rs.Close
    Set rs = Nothing
    objAccess.Quit
    Set objAccess = Nothing
    Set xlSheet = Nothing
    Set xlBook = Nothing
    Exit Sub
 
SubError:
    Application.StatusBar = ""
    MsgBox "RefreshData - UpdateData VBA error: " & vbCrLf & Err.Number & " = " & Err.Description
    Resume SubExit
   
End Sub

참고 : 암호화 된 .accdb와 함께 작동하는 유일한 방법이기 때문에이 답변 에서 설명한 대로 개체를 사용 하고 있습니다.

답변

Gustav Nov 17 2020 at 07:26

연결을 다시 확인하겠습니다.

또한 테스트의 경우 간단한 테스트 쿼리를 열어 쿼리 문제를 배제합니다.

    SQL = "SELECT Id FROM MSysObjects"
    ' Execute our query and populate the recordset
    MsgBox objAccess.CurrentProject.Connection
    Set rs = objAccess.CurrentProject.Connection.Execute(SQL)
    MsgBox rs!Id