3

I'm trying to erase table content and replace it with new content in an excel sheet.

The code doesn't raise any errors however everytime I run it, it inserts some blanck cells before the source table.

The 'base.xlsx' table sheet looks like this :

base

If target.xlsx is void before running the code I get what I want however if I run it again I get this :

target

Here is the code :

Sub SQLQUERY()

    Dim Cn As ADODB.Connection
    Dim QUERY_SQL As String
    Dim ExcelCn As ADODB.Connection

    SourcePath = "C:\Path\to\base.xlsx"
    TargetPath = "C:\Path\to\target.xlsx"

    CHAINE_HDR = "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] "

    Set Cn = New ADODB.Connection

    STRCONNECTION = _
    "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source='" & SourcePath & "';" & _
    "Mode=Read;" & _
    "Extended Properties=""Excel 12.0;"";"

    Colonnes = "[Col#1], Col2"

    QUERY_SQL = _
    "SELECT " & Colonnes & " FROM [base$] " & _
    "IN '" & SourcePath & "' " & CHAINE_HDR

    MsgBox (QUERY_SQL)

    Cn.Open STRCONNECTION

    Set ExcelCn = New ADODB.Connection
    ExcelCn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                   "Data Source=" & TargetPath & ";" & _
                   "Extended Properties=""Excel 12.0;HDR=YES;"""

    ExcelCn.Execute "DROP TABLE [sheet$]"

    ExcelCn.Execute "CREATE TABLE [sheet$] ([C1] Float, [C2] Float, [C3] Float)"

    Cn.Execute "INSERT INTO [sheet$] (C1, C3) IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL

    '--- Fermeture connexion ---

    Cn.Close
    ExcelCn.Close


End Sub

1 Answer 1

1

After some research I discovered what's going on with the code. When Drop Table is executed Excel keep the "active range" and thus INSERT INTO will insert data after the active range.

To counter this we need to specify a range with the table name :

ExcelCn.Execute "DROP TABLE [sheet$]"

ExcelCn.Execute "CREATE TABLE [sheet$] ([C1] Float, [C2] Float, [C3] Float)"

Cn.Execute "INSERT INTO [sheet$A1:ZZ1] (C1, C3) IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL

'--- Fermeture connexion ---

Note the [sheet$A1:ZZ1] in the sql statement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.