2010-04-02 134 views
1

我想使用Excel VBA自動創建現有SQL數據庫中的SQL表。使用Excel VBA創建SQL表

我在這邊遇到下面的代碼。

Private Sub CreateDatabaseFromExcel() 

Dim dbConnectStr As String 
Dim Catalog As Object 
Dim cnt As ADODB.Connection 
Dim dbPath As String 
Dim tblName As String 

'Set database name in the Excel Sheet 
dbPath = ActiveSheet.Range("B1").Value 'Database Name 
tblName = ActiveSheet.Range("B2").Value 'Table Name 

dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";" 

'Create new database using name entered in Excel Cell ("B1") 
Set Catalog = CreateObject("ADOX.Catalog") 
Catalog.Create dbConnectStr 
Set Catalog = Nothing 

'Connect to database and insert a new table 
Set cnt = New ADODB.Connection 
With cnt 
    .Open dbConnectStr 
    .Execute "CREATE TABLE tblName ([BankName] text(50) WITH Compression, " & _ 
      "[RTNumber] text(9) WITH Compression, " & _ 
      "[AccountNumber] text(10) WITH Compression, " & _ 
      "[Address] text(150) WITH Compression, " & _ 
      "[City] text(50) WITH Compression, " & _ 
      "[ProvinceState] text(2) WITH Compression, " & _ 
      "[Postal] text(6) WITH Compression, " & _ 
      "[AccountAmount] decimal(6))" 
End With 
Set cnt = Nothing 

End Sub 

但是我不能成功地使它工作?

我想要做的是實際使用Excel來創建一個表而不是數據庫?數據庫已經存在。我只想創建一個新表。該表的名稱將參考工作表1中的單元格A1。

有人可以請幫忙。

+0

你會得到什麼錯誤? – Oded 2010-04-02 12:28:24

+0

你說「在現有SQL數據庫中自動創建SQL表」,但也嘗試創建數據庫。你想要做什麼? – gbn 2010-04-02 12:36:59

回答

0

只是註釋這些行了:

Set Catalog = CreateObject("ADOX.Catalog") 
Catalog.Create dbConnectStr 
Set Catalog = Nothing 

這應該這樣做,因爲這些行創建新的數據庫。後面的代碼只是打開它並創建你想要的表。

+0

嗨,謝謝你的幫助。 一旦我註釋掉這些行,我會在dppath =上得到一個錯誤。 任何想法,爲什麼? 再次感謝您的幫助 – user307655 2010-04-02 13:01:32

+0

單元格B1的價值是什麼?應該是數據庫的路徑! – dwo 2010-04-02 21:19:24