View Single Post
 
Old 01-26-2019, 10:23 AM
Kenneth Hobson Kenneth Hobson is offline Windows 10 Office 2016
Advanced Beginner
 
Join Date: Jun 2018
Posts: 37
Kenneth Hobson is on a distinguished road
Default

Change start range, and name for query and listobject to suit. This makes it easier to do more than one import into a workbook.

So the difference here is going beyond the macro recorder. For future code like this, you can more readily see how it is structured rather than long lines of code.
Code:
Sub Main()
  Dim q$, f$, nm$, r As Range
  
  q = """"
  nm = "B"
  Set r = Range("B8")
    
  f = "let" & vbCrLf & "Source = Csv.Document(File.Contents(" & _
  q & ThisWorkbook.Path & "\x.csv" & q & ")," & _
  "[Delimiter="","", Columns=10, Encoding=65001, QuoteStyle=QuoteStyle.None])," & _
  vbCrLf & "#""Promoted Headers"" = Table.PromoteHeaders(" & _
  "Source, [PromoteAllScalars=true])," & vbCrLf & _
  "#""Changed Type"" = Table.TransformColumnTypes(" & _
  "#""Promoted Headers" & _
  """,{{""Lot_No"", Int64.Type}, {""Unit"", type text}, " & _
  "{""Cont_UE"", Int64.Type}, {""Int_UE"", Int64.Type}, " & _
  "{""Owners_Name"", type text}, {""Owners_Address"", type text}, " & _
  "{""Owners_Phone"", type text}, {""Owners_Email"", type text}, " & _
  "{""Committee_Member"", type text}, {""Balance"", type text}})" & vbCrLf & _
  "in" & vbCrLf & "#""Changed Type"""
    
  ActiveWorkbook.Queries.Add nm, f
    
  With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;" & _
    "Data Source=$Workbook$;Location=" & nm & ";" & _
    "Extended Properties=""""", _
    Destination:=r).QueryTable
      .CommandType = xlCmdSql
      .CommandText = Array("SELECT * FROM [" & nm & "]")
      .RowNumbers = False
      .FillAdjacentFormulas = False
      .PreserveFormatting = True
      .RefreshOnFileOpen = False
      .BackgroundQuery = True
      .RefreshStyle = xlInsertDeleteCells
      .SavePassword = False
      .SaveData = True
      .AdjustColumnWidth = True
      .RefreshPeriod = 0
      .PreserveColumnInfo = True
      .ListObject.DisplayName = nm
      .Refresh BackgroundQuery:=False
  End With
    
    ActiveWindow.SmallScroll Down:=-3
    Application.CommandBars("Queries and Connections").Visible = False
    ActiveWorkbook.Save
End Sub
Reply With Quote