Home » excel » How to create a new sheet/table in an .xlsx file using ADO in excel vba

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

Posted by: admin May 14, 2020 Leave a comment

Questions:

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. 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. I’ve used test and testName and after digging around I am stumped. 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:

CREATE TABLE [test$] ([Col1] Float, [Col2] Float)

and then a runtime error stating

[Microsoft] [ODBC Excel Driver] ‘test$’ is not a valid name

I’ve searched that error also but still can find out why this isn’t working. Any help is really appreciated!

How to&Answers:

The below example shows how to create a workbook and add worksheets using 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

Using ADOX with Excel Data

Microsoft ACE OLEDB 12.0 connection strings