2014-10-01 57 views
0

使用QueryDef時,我收到以下錯誤「對象 變量或塊變量未設置」。當我將strSQL的輸出複製到新的查詢時,它工作正常。請協助解決此錯誤。MS Access VBA QueryDef - 使用塊變量未設置錯誤

運行以下行時發生錯誤;

Set qryDef = dbs.CreateQueryDef(strQueryName, strSQL) 

見下

Private Sub ComboReclassify_AfterUpdate() 

Dim dbs As Database 
Dim strSQL As String 
Dim strQueryName As String 
Dim qryDef As QueryDef 

strQueryName = "qryST_ReclassifyAttribute" 

Dim attr As String 
Dim ValueID As Integer 
attr = [Forms]![frm_tblST_AttributesReclassification]![ComboItemAttributes] 
ValueID = [Forms]![frm_tblST_AttributesReclassification]![ComboReclassify] 

strSQL = "UPDATE dbo_tblST_DepartmentsAttributes SET " & (attr) & " = " & ValueID & " WHERE dbo_tblST_DepartmentsAttributes.id = 1" 

Set qryDef = dbs.CreateQueryDef(strQueryName, strSQL) 

DoCmd.OpenQuery "qryST_ReclassifyAttribute" 

End Sub 

回答

2

整個代碼,您似乎已經錯過了設置DBS對象。

Private Sub ComboReclassify_AfterUpdate() 
    Dim dbs As Database 
    Dim strSQL As String 
    Dim strQueryName As String 
    Dim qryDef As QueryDef 

    strQueryName = "qryST_ReclassifyAttribute" 

    Dim attr As String 
    Dim ValueID As Integer 
    attr = [Forms]![frm_tblST_AttributesReclassification]![ComboItemAttributes] 
    ValueID = [Forms]![frm_tblST_AttributesReclassification]![ComboReclassify] 

    strSQL = "UPDATE dbo_tblST_DepartmentsAttributes SET " & (attr) & " = " & ValueID & " WHERE dbo_tblST_DepartmentsAttributes.id = 1" 

    'You have not set the dbs object. That is the problem 
    Set dbs = CurrentDB 
    Set qryDef = dbs.CreateQueryDef(strQueryName, strSQL) 

    DoCmd.OpenQuery "qryST_ReclassifyAttribute" 
End Sub 

一旦你設置它。它應該正常工作!

相關問題