How to put query results into a datatable with Excel VBA and ADO?

后端 未结 2 1343
滥情空心
滥情空心 2021-01-22 11:51

I want to use ADO via ODBC to pull records from a database table and put them in an Excel worksheet. I can do this. Ultimately, I want the data to be contained within an Excel T

相关标签:
2条回答
  • 2021-01-22 12:42

    Something like this?

    Add this code after you have imported the data. I am assuming the following. Please amend accordingly.

    • The data is imported in Cell A1 of Sheet1

    • Row 1 has column Headers

      Sub Sample()
      
          Dim LastRow As Long, LastCol As Long
          Dim ws As Worksheet
          Dim rng As Range
      
          Set ws = Sheets("Sheet1")
      
          LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
          LastCol = ws.Cells(1, Columns.Count).End(xlToLeft).Column
      
          Set rng = Range("$A$1:$" & Split(Cells(, LastCol).Address, "$")(1) & "$" & LastRow)
      
          With ws
              .ListObjects.Add(xlSrcRange, rng, , xlYes).Name = "Table1"
              .ListObjects("Table1").TableStyle = "TableStyleLight2"
          End With
      
      End Sub
      
    0 讨论(0)
  • 2021-01-22 12:43

    If you click the From Other Sources button on the Data tab you should see your ODBC listed. You can then specify the table to connect to. You will then have a refreshable Table that contains your data, in other words it combines what you're already doing with what you want to do into one step. Based on what you said in your comments I think this is the way to go, but let me know if I'm missing something.

    0 讨论(0)
提交回复
热议问题