views:

28

answers:

1

I do an import data from a query I created in MS Query. Lets say the columns are in order A,B,C,D,E,F in the Query Editor. Once the I save the query, return data to Excel, the imported data has a new column order

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

Any ideas on how to solve this issue?

Thanks guys. Assume variables are defined correctly and disregard what the code is trying to do if you want, the preserving 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
+1  A: 

There are two properties of the QueryTable object called PreserveColumnInfo and PreserveFormatting, which should help you out. (There's also AdjustColumnWidth, but I'm not sure if you need to worry about that one). You should be able to use code similar to the following to help preserve the column information:

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
Ben McCormack
haha hello again Ben, with a 0, I get object-defined error, with a 1 I get script out of range error...any thoughts? Thanks!
Ehsan
@Ehsan do you know which line is throwing the error? 0 is probably the correct number to use if you get a script out of range error when using 1. Make sure you are using this while on the worksheet that has the data in it. I wish I could remember what else to check, but without a database-connected Excel sheet, I'm not sure what else to look at.
Ben McCormack
It throws it on the Set qt = ws.QueryTables(0)...I'm doing a for each loop. I provided the code. Thanks Ben
Ehsan
I noticed in your code that you're setting it to QueryTables(1). I thought you script out of range error when you used 1?. Also, if you're looping through all of the query tables in your workbook, make sure each sheet has a query table in it or else the code will blow up.
Ben McCormack
Also, don't forget you should dim the query table before you set it: `Dim qt As QueryTable`
Ben McCormack
Oh well neither digits work so I didn't bother with the edit. Anyway Each sheet has a query table except the Master Sheet.
Ehsan
Yep all variables defined :)
Ehsan