VBA - 表创建时出错

时间:2013-10-30 03:15:18

标签: vba ms-access

Sub CreateTable()
MsgBox "Like this?"
    'Add Reference to Microsoft ActiveX Data Objects 2.x Library
    Dim strConnectString        As String
    Dim objConnection           As ADODB.Connection
    Dim strDbPath               As String
    Set objConnection = CreateObject("ADODB.Connection")
    'Set database name and DB connection string--------
    strDbPath = "E:\Books\Works\Newdb.mdb"
    '==================================================
    MsgBox "created"
    strConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDbPath & ";"
    MsgBox "created2"
    'Connect Database; insert a new table
    'Set objConnection = New ADODB.Connection
    With objConnection
        .Open strConnectString
        .Execute "CREATE TABLE MyTable ([EmpName] text(50) WITH Compression, " & _
                 "[Address1] text(150) WITH Compression, " & _
                 "[Address2] text(150) WITH Compression, " & _
                 "[City] text(50) WITH Compression, " & _
                 "[State] text(2) WITH Compression, " & _
                 "[PIN] text(6) WITH Compression, " & _
                 "[SIN] decimal(6))"
    End With

End Sub

我收到如下错误

****Run-Time Error  '-2147467259 (80004005)':
Automation error
Unspecified error****

1 个答案:

答案 0 :(得分:1)

试过&经过测试的代码(适用于mdb)

Sub CreateTable()
'Add Reference to Microsoft ActiveX Data Objects 2.x Library
    Dim strConnectString As String
    Dim objConnection As ADODB.Connection
    Dim strDbPath As String

    'Set database name and DB connection string--------
    strDbPath = "E:\Books\Works\Newdb.mdb"
    '==================================================

    strConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDbPath & ";"

    'Connect Database; insert a new table
    Set objConnection = New ADODB.Connection
    With objConnection
        .Open strConnectString

        strSQL = "CREATE TABLE MyTable " & _
                 "(EmpName TEXT(150)," & _
                 "Address1 TEXT(150)," & _
                 "Address2 TEXT(150)," & _
                 "City TEXT(50)," & _
                 "State TEXT(2)," & _
                 "PIN TEXT(6)," & _
                 "SIN number)"

        .Execute strSQL
    End With

    Set objConnection = Nothing

End Sub