2017-08-22 101 views
2

當執行移動到不同模塊中的子時,我的公共變量正在丟失範圍。我無法理解爲什麼會發生這種情況。公共變量超出範圍

模塊A:

Option Compare Database 

Public db As DAO.Database 
Public xlApp As Excel.Application 

Sub Main() 

Dim db As DAO.Database 

Set db = CurrentDb 

ProcessFiles ' upload the data from the report files 
AppendToPentana ' transfer the data from the main tables to the pentana export table 
ProduceFinalExport ' export the final data to Excel 

End Sub 

模塊B:

Sub ProcessFiles() 

Dim recSet As Recordset 

' open a recordset containing keywords to look for in the file names to identify the area 
Set recSet = db.OpenRecordset("tblFiles") 

' rest of code 

End Sub 

在模塊B中的可變分貝已經設置爲Nothing和我得到一個對象REF錯誤。我試過使用舊版的「全局」聲明而不是使用相同的結果。

公共變量是常用的,我不知道這裏出了什麼問題。

+0

'全局'*與*公共*完全相同(除了'公共'無法使用')。數十年前,'Public'已經過時,'Global'已經過時。 –

回答

6
Sub Main() 

Dim db As DAO.Database 

Set db = CurrentDb 

您有一個額外的當地變量dbMain,這是你設置的一個。局部變量優先於全局變量。

只需從Main刪除Dim行,它將工作。

+0

Doh!我需要一杯咖啡:)謝謝 – Absinthe

+0

爲了記錄,整個刪除'Dim'行。不要只是刪除'昏暗'(對於任何未來可能遇到的人)。 –