2016-11-28 72 views
2

我已經繼承了VBA項目,並試圖調試我收到的錯誤:Invalid use of Null。過了一段時間,我找到了發生錯誤的地方,但還沒有找到問題的具體罪魁禍首和/或解決方案。請參閱以下的這段(行拋出異常標註有評論):VBA無效使用null

Dim db As Database, wsp As Workspace 
    Dim retVal As Variant 
    Dim tableType As Long 

    'Check to see if the table name exists in the zLinked_Tables table; if it does, that means its a SQL table 
    If DCount("*", "[zLinked_Tables]", "[LocalName] = '" & TableName & "' AND [ObjectType] = 'Table'") > 0 Then 
     'SQL Table 
     retVal = ExecuteSPT("TRUNCATE TABLE [" & TableName & "]", 0) 'truncate the table via passthrough query on server 
     If KeyColumn <> "" Then 
      retVal = ExecuteSPT("DBCC CHECKIDENT([" & TableName & "],RESEED,1)", 0) 'reset the identity column value via passthrough query on server 
     End If 
    Else 
     'MS Access Table 
     tableType = DLookup("[Type]", "[MSysObjects]", "[Name] = '" & TableName & "'") 
     DoCmd.SetWarnings False 
     DoCmd.RunSQL "DELETE * FROM [" & TableName & "]" 'delete all records from table 
     If KeyColumn <> "" Then 
      DoCmd.SetWarnings True 
      If tableType = 1 Then 'Resident/Local 
       Set db = CurrentDb 
       db.Execute "ALTER TABLE [" & TableName & "] ALTER COLUMN [" & KeyColumn & "] COUNTER(1,1)" 
      Else 'Linked Table 
       Set wsp = DBEngine.Workspaces(0) 
       Set db = wsp.OpenDatabase(DLookup("[Database]", "[MSysObjects]", "[Name] = '" & TableName & "'")) 'ERROR THROWN ON THIS LINE 
       db.Execute "ALTER TABLE [" & TableName & "] ALTER COLUMN [" & KeyColumn & "] COUNTER(1,1)" 'reset the autonumber column value 
      End If 
      DoCmd.SetWarnings False 
      Set db = Nothing 
     End If 
    End If 
    Exit Function 

注意,我已檢查了TableName變量,它不爲空,這是一個有效的表名

回答

2

你使用DLookup返回在「數據庫」字段中MSYSObjects沒有值(NULL)一行。在立即窗口和執行程序中鍵入以下內容。您需要添加代碼以允許這種可能性。

我假設你試圖獲得完整的路徑?

?(DLookup("[Database]", "[MSysObjects]", "[Name] = '" & "Table1" & "'")) 
2

有幾件事情發生在這條線上。除了檢查TableName爲空,您還應該檢查是否wsp null?無論什麼原因,Set wsp = DBEngine.Workspaces(0)都會失敗嗎?

dlookup失敗了嗎? DLookup("[Database]", "[MSysObjects]", "[Name] = '" & TableName & "'")。如果是零,這意味着要傳遞nullwsp.OpenDatabase()它給你看到的錯誤:

enter image description here