2013-11-14 41 views
0

我該如何通過Excel vba檢查給定的表格(稱爲Items)是否在特定的Access數據庫中。如果表格不在Excel中的Access數據庫中VBA

我已經建立了連接從Excel表到兩個不同的數據庫,[A] & [B],通過Excel VBA和我的其他代碼工作正常。

迄今爲止,最接近我已經能夠在網上找到的是:

If IsNull(DLookup("[Name]", "MSysObjects", "[Name]='Items'")) Then 

這個代碼不指定我想搜索的數據庫。有沒有一種方法可以編寫一個語句,只有在數據庫[B]中找不到表Items才能運行?這段代碼如何編寫?

我沒有問題引用數據庫。我的大部分代碼都是從Excel運行的SQL,並且我能夠在各個數據庫特定的字段中引用各種條目。我只是想找一行說:「如果這個表不存在這個數據庫,那麼創建一個表這個名字」。有沒有可能我可以寫一個SQL字符串,甚至是一個try ... catch方法?

任何幫助,將不勝感激

+0

DLookup功能特定於Access,我認爲。你能展示你如何「建立連接」從Excel的Access數據庫? – Floris

+0

看看http://stackoverflow.com/questions/9083232/writing-excel-vba-to-receive-data-from-access中給出的代碼 - 它顯示了Excel如何引用特定數據庫(並且沒有爲什麼你不能使用這種方法有兩個數據庫)。但它不使用'DLookup' ... – Floris

+0

謝謝弗洛里斯。我更新了我的問題。 – user2937941

回答

0

你也許可以使用On Error技術(這是一個有點像try...catch,但後者沒有在VBA存在)。例如:

On Error GoTo whoa 
Set db = OpenDatabase(DBFullName) ' use the name of [A] or [B] here. 
Set rs = db.OpenRecordset(*** your expression to get something from db ***) 
' if you get past this line, then reading the data went OK 
MsgBox "Everything is fine" 
' it is possible that the above will not throw an error, but returns something "empty" 
' I would put a breakpoint in the code and step through, then examine `rs` 
' both for the case where the table exists, and where it doesn't 
Exit Function 
whoa: 
MsgBox "Something went horribly wrong: error is " & Err.Description 
' this is where you would go if you were not able to get the data 

很明顯你會這樣做[A]和[B]找出表存在的位置(如果有的話)。我沒有在我的機器上使用Access,因此我不能輕易地爲您測試,對不起。

+0

非常感謝Floris!我稍微修改了一下,以便代碼嘗試創建表。如果創建不起作用,那麼假定表存在,恢復代碼。這一切都有效。 – user2937941

+0

太棒了。很高興這是所有的工作。 – Floris

+0

你可以在VBA中模擬一個TRY CATCH塊請看這裏 http://stackoverflow.com/q/30991653/4413676 – HarveyFrench

相關問題