简体   繁体   English

如何在 Excel vba 中使用 ADO 在 .xlsx 文件中创建新工作表/表格

[英]How to create a new sheet/table in an .xlsx file using ADO in excel vba

Hi I'm trying to create a function that will store a range of data selected by a user along with a user's custom name and then using ADO the data will be stored in a new Excel sheet with the user's custom name as the sheet name.嗨,我正在尝试创建一个函数,该函数将存储用户选择的一系列数据以及用户的自定义名称,然后使用 ADO 将数据存储在新的 Excel 工作表中,并将用户的自定义名称作为工作表名称。 So far I've gotten an ADO connection working and can read and write data to the .xlsx file but when I try and create a new sheet by creating a new table I get an error that my sheet name is not correct.到目前为止,我已经建立了一个 ADO 连接,并且可以读取和写入数据到 .xlsx 文件,但是当我尝试通过创建新表来创建新表时,我收到一个错误,表明我的表名称不正确。 I've used test and testName and after digging around I am stumped.我已经使用了testtestName并且在挖掘之后我被难住了。 Here is a chunk of my code:这是我的一段代码:

Sub AddSheet()

    Dim DataName As String, SRange As Variant, qry As String, SCols As Integer, SRows As Integer

    DataName = InputBox("Enter Your Data Name:")
    Set SRange = Application.Selection
    Set SRange = Application.InputBox("Select your data to be saved:", xTitleId, SRange.Address, Type:=8)
    SCols = SRange.Columns.Count 'new
    SRows = SRange.Rows.Count 'new
    'creates the query to create a new sheet/table for the data
    qry = "CREATE TABLE [" & DataName & "$] ("
    For i = 1 To SCols
        qry = qry & "[Col" & i & "] Float"
        If i <> SCols Then
            qry = qry & ", "
        End If
    Next i
    qry = qry + ")"
    SQLUpdateData qry

End Sub

'function that executes the SQL query
Function SQLUpdateData(qry As String) As Variant

    Dim FileName As String, sconnect As String
    Dim cnn As New ADODB.Connection
    Dim objMyCmd As ADODB.Command

    Set cnn = New ADODB.Connection
    Set objMyCmd = New ADODB.Command
    FileName = "c:\Users\" & Environ("Username") & "\AppData\Roaming\Microsoft\AddIns\DataStorage.xlsx"
    sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & FileName & ";HDR=Yes';"
    cnn.Open sconnect
    objMyCmd.CommandType = adCmdText
    objMyCmd.CommandText = qry
    objMyCmd.ActiveConnection = cnn
    MsgBox qry
    objMyCmd.Execute
    Set objMyCmd = Nothing
    Set cnn = Nothing

End Function

So far I've printed out the query and it looks ok before execution.到目前为止,我已经打印出查询,并且在执行前看起来没问题。 For example if the user chooses the name test I get the following query output:例如,如果用户选择名称test我会得到以下查询输出:

CREATE TABLE [test$] ([Col1] Float, [Col2] Float)创建表 [test$]([Col1] 浮点数,[Col2] 浮点数)

and then a runtime error stating然后一个运行时错误说明

[Microsoft] [ODBC Excel Driver] 'test$' is not a valid name [Microsoft] [ODBC Excel 驱动程序] 'test$' 不是有效名称

I've searched that error also but still can find out why this isn't working.我也搜索了该错误,但仍然可以找出为什么这不起作用。 Any help is really appreciated!任何帮助真的很感激!

The below example shows how to create a workbook and add worksheets using ADOX:以下示例显示了如何使用 ADOX 创建工作簿和添加工作表:

Option Explicit

Sub Test()

    ' Add reference
    ' Microsoft ADO Ext. 6.0 for DDL and Security

    Dim cat As ADOX.Catalog
    Dim tbl As ADOX.Table
    Dim col As ADOX.Column

    Set cat = New ADOX.Catalog
    cat.ActiveConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\test.xlsx;Extended Properties=Excel 12.0 Xml"
    Set tbl = New ADOX.Table
    tbl.Name = "TestTable"
    Set col = New ADOX.Column
    With col
        .Name = "Col1"
        .Type = adVarWChar
    End With
    tbl.Columns.Append col
    cat.Tables.Append tbl

End Sub

Some useful links:一些有用的链接:

About ADOX 关于 ADOX

Using ADOX with Excel Data 将 ADOX 与 Excel 数据结合使用

Microsoft ACE OLEDB 12.0 connection strings Microsoft ACE OLEDB 12.0 连接字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM