Excel VBA创建SQL表

时间:2010-04-02 13:35:36

标签: sql excel excel-vba vba

我找到了以下代码,它应该在SQl数据库中创建一个SQL表。

数据库在dbpath中指定,要创建的表位于tblname

但是,当我运行此代码时,我在连接到正确的SQL数据库时遇到问题。

例如,如果我将dbpath指定为“WIN2k8 \ Test \ ABC”,即机器名称为WIN2k8,则sql实例为Test数据库为ABC。

由于某种原因,它一直在保存dbpath,就像我保存Excel工作簿然后WIN2k8 \ test \ abc。

有人可以帮忙吗?

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  

2 个答案:

答案 0 :(得分:0)

Jet.OLEDB提供程序用于MS Access。尝试使用SQL Server连接字符串,如果这是您要连接到的那个。您可以在http://www.connectionstrings.com/找到不同类型的连接字符串。

希望有所帮助

答案 1 :(得分:0)

您还可以尝试在以下位置描述的udl文件技巧 - 您也可以尝试使用udl文件方法获取连接字符串 - http://msdn.microsoft.com/en-us/library/aa140076%28office.10%29.aspx