Excel imports SQL data but reorders 1 column after import

I am importing data from a query that I created in MS Query. Suppose the columns are in order A, B, C, D, E, F in the query editor. After saving the query, return the data to Excel, the imported data has a new column order

A, B, C, F, D, E - note that column F moved where D was.

Any ideas on how to solve this problem?

Thanks guys. Suppose the variables are defined correctly and ignore what the code is trying to do if you want, the saving part is not working.

For Each wks In ThisWorkbook.Worksheets

  Set qt = wks.QueryTables(1)
  qt.PreserveColumnInfo = True
  qt.PreserveFormatting = True


        If wks.Name <> "Master" And wks.Name <> "Parameters" Then


        wks.Range("A2:A1000").EntireRow.Copy Destination:=Worksheets("Master").Range("A65536").End(xlUp).Offset(1, 0)




        End If
    Next wks
+3
source share
1 answer

QueryTable, PreserveColumnInfo PreserveFormatting, . ( AdjustColumnWidth, , ). , , :

Sub PreserveQueryTable()
    Dim ws As Worksheet
    Dim qt As QueryTable

    Set ws = ActiveSheet

    Set qt = ws.QueryTables(0) ' <== I am not sure if this should be a     '
                               '     0 or a 1. I think it is a 0.          '

    qt.PreserveColumnInfo = True
    qt.PreserveFormatting = True

End Sub
+4

Source: https://habr.com/ru/post/1758449/


All Articles