Query not pulling right info when running in VBA

Holley

Board Regular
Joined
Dec 11, 2019
Messages
155
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
Hello All! As always, many thanks for all your past help!! I have tried and tried, and for my life, I cannot figure out why the code below is not working correctly. As written, it works flawlessly. I need to exclude anything starting with "8" in column B. Runs like a charm - but now I need also to exclude anything starting with a "9". When I add this to the query, I get no data, but when I run it manually, it works. There can be hundreds of rows of data. Below is a small sampling and the current code. Any suggestions would be most appreciated!
DateNBRInfo
07/07/24 547 578R
07/08/24 578 4589
07/07/24 001 1234
07/07/24 002 1256
07/07/24 003 578R
07/08/24 004 4589
07/07/24 005 1234
07/07/24 006 1256
07/07/24 007 578R
07/08/24 008 4589
07/07/24 009 1234
07/07/24 010 1256
07/07/24 011 578R
07/08/24 012 4589
08/14/249001234
08/14/249011235
08/14/248016789
08/14/248020123


VBA Code:
Sub codes()

    ' Select File
    Dim myfile As Variant
    myfile = Application.GetOpenFilename( _
                                          FileFilter:="Text Files (*.lin), *.lin", _
                                          Title:="Select text file", _
                                          ButtonText:="Open")
    If myfile = False Then Exit Sub
    Dim my_workbook As Workbook, my_worksheet As Worksheet
    ' First digit in array is character and 2nd is format.
    Workbooks.OpenText Filename:=myfile, _
        Origin:=437, StartRow:=6, DataType:=xlFixedWidth, FieldInfo:=Array( _
        Array(0, 2), Array(9, 2), Array(13, 2), Array(18, 2)) _
        , TrailingMinusNumbers:=True
    Set my_workbook = ActiveWorkbook
    Set my_worksheet = my_workbook.Sheets(1)
  
    With my_worksheet
        .Columns("D").EntireColumn.Delete
        .Columns("A:C").Select
        Application.CutCopyMode = False
        .ListObjects.Add(xlSrcRange, .Range("$A:$C"), , xlNo).Name = "Table1"
 
        ' Create Query
        .Columns("A:C").Select
        .Parent.Queries.Add Name:="Table1", Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}})," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each [Column2] <> null and [Column2] <> """")," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows1"" = Table.SelectRows(#""F" & _
        "iltered Rows"", each not Text.StartsWith([Column2], ""8""))," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each ([Column2] <> ""-05"" and [Column2] <> ""H IN"" and [Column2] <> ""NBR""))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"""
    End With
      
    Dim second_sheet As Worksheet
    Set second_sheet = my_workbook.Worksheets.Add
  
    With second_sheet.ListObjects.Add(SourceType:=0, Source:= _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Table1;Extended Properties=""""" _
        , Destination:=second_sheet.Range("$A$1")).QueryTable
        .CommandType = xlCmdSql
        .CommandText = Array("SELECT * FROM [Table1]")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Table1_2"
         my_workbook.RefreshAll
    End With
 
   ' Copy and Paste_into_new_sheet
    Dim lastRow As Long, CopyRange As Range
    Dim PasteWorkbook As Workbook, PasteSheet As Worksheet, PasteRange As Range
    With second_sheet
        lastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        Set CopyRange = .Range(.Cells(2, 1), .Cells(lastRow, 3))
    End With
  
    MsgBox "LastRow: " & lastRow & ", and CopyRange: " & CopyRange.Address
    Set PasteWorkbook = Workbooks.Open(Filename:= _
        "https://company-my.sharepoint.com/personal/myname_company_com/Documents/Desktop/file2.xlsm")
    'Set PasteWorkbook = Workbooks.Add ' For testing
    Set PasteSheet = PasteWorkbook.Sheets(1) ' YOU MIGHT NEED TO CHANGE THIS
    CopyRange.Copy Destination:=PasteSheet.Range("A5")
 
End Sub
 

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
Didnt test but try this:

below my_workbook.RefreshAll enter the following line.
Application.CalculateUntilAsyncQueriesDone
 
Upvote 0
No luck. I edited the above code to remove anything starting with 8 or 9 and it returned no data when running the macro. Even after adding the above line. This is how I edited the query part...

VBA Code:
  ' Create Query
        .Columns("A:C").Select
        .Parent.Queries.Add Name:="Table1", Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{""DATE"", type text}, {""NBR"", type text}, {""CLNT"", type text}})," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each ([NBR] <> null and [NBR] <> ""CH IN"" and [NBR] <> ""NBR""))," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows1"" = Table.Selec" & _
        "tRows(#""Filtered Rows"", each not Text.Contains([NBR], ""-""))," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each not Text.StartsWith([NBR], ""8"") and not Text.StartsWith([NBR], ""9""))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"""
    ActiveWorkbook.Worksheets.Add
    End With
 
Upvote 0
I think you have to have something wrong in your query string.
I'm afraid I found it easier to follow and edit the string by doing it long hand so if you replace the next section with my code below it and add the function I have under that it should work. The main changes inside the with statement were to reduce the table to be just the used range and not all 1M rows.

Replace this:
VBA Code:
    With my_worksheet
        .Columns("D").EntireColumn.Delete
        .Columns("A:C").Select
        Application.CutCopyMode = False
        .ListObjects.Add(xlSrcRange, .Range("$A:$C"), , xlNo).Name = "Table1"
 
        ' Create Query
        .Columns("A:C").Select
        .Parent.Queries.Add Name:="Table1", Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}})," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each [Column2] <> null and [Column2] <> """")," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows1"" = Table.SelectRows(#""F" & _
        "iltered Rows"", each not Text.StartsWith([Column2], ""8""))," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each ([Column2] <> ""-05"" and [Column2] <> ""H IN"" and [Column2] <> ""NBR""))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"""
    End With

With this:
Rich (BB code):
    With my_worksheet
        .Columns("D").EntireColumn.Delete
        Dim rngTbl As Range
        Set rngTbl = Intersect(.Columns("A:C"), .UsedRange)
        Application.CutCopyMode = False
        .ListObjects.Add(xlSrcRange, rngTbl, , xlNo).Name = "Table1"
 
        ' Create Query
        .Parent.Queries.Add Name:="Table1", Formula:=get_QryString
  
    End With

Add this:

Rich (BB code):
Function get_QryString() As String

    Dim strQry As String
  
    strQry = "let"
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content],"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}}),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each [Column2] <> null and [Column2] <> """"),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows1"" = Table.SelectRows(#""Filtered Rows"", each not Text.StartsWith([Column2], ""8"")),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each not Text.StartsWith([Column2], ""9"")),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows3"" = Table.SelectRows(#""Filtered Rows2"", each ([Column2] <> ""-05"" and [Column2] <> ""H IN"" and [Column2] <> ""NBR""))"
  
    strQry = strQry & Chr(13) & "" & Chr(10)
    strQry = strQry & "in"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows3"""
  
    get_QryString = strQry

End Function
 
Upvote 0
I think you have to have something wrong in your query string.
I'm afraid I found it easier to follow and edit the string by doing it long hand so if you replace the next section with my code below it and add the function I have under that it should work. The main changes inside the with statement were to reduce the table to be just the used range and not all 1M rows.

Replace this:
VBA Code:
    With my_worksheet
        .Columns("D").EntireColumn.Delete
        .Columns("A:C").Select
        Application.CutCopyMode = False
        .ListObjects.Add(xlSrcRange, .Range("$A:$C"), , xlNo).Name = "Table1"
 
        ' Create Query
        .Columns("A:C").Select
        .Parent.Queries.Add Name:="Table1", Formula:= _
        "let" & Chr(13) & "" & Chr(10) & "    Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content]," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}})," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each [Column2] <> null and [Column2] <> """")," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows1"" = Table.SelectRows(#""F" & _
        "iltered Rows"", each not Text.StartsWith([Column2], ""8""))," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each ([Column2] <> ""-05"" and [Column2] <> ""H IN"" and [Column2] <> ""NBR""))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Filtered Rows2"""
    End With

With this:
Rich (BB code):
    With my_worksheet
        .Columns("D").EntireColumn.Delete
        Dim rngTbl As Range
        Set rngTbl = Intersect(.Columns("A:C"), .UsedRange)
        Application.CutCopyMode = False
        .ListObjects.Add(xlSrcRange, rngTbl, , xlNo).Name = "Table1"
 
        ' Create Query
        .Parent.Queries.Add Name:="Table1", Formula:=get_QryString
 
    End With

Add this:

Rich (BB code):
Function get_QryString() As String

    Dim strQry As String
 
    strQry = "let"
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content],"
 
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}}),"
 
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each [Column2] <> null and [Column2] <> """"),"
 
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows1"" = Table.SelectRows(#""Filtered Rows"", each not Text.StartsWith([Column2], ""8"")),"
 
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each not Text.StartsWith([Column2], ""9"")),"
 
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows3"" = Table.SelectRows(#""Filtered Rows2"", each ([Column2] <> ""-05"" and [Column2] <> ""H IN"" and [Column2] <> ""NBR""))"
 
    strQry = strQry & Chr(13) & "" & Chr(10)
    strQry = strQry & "in"
 
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows3"""
 
    get_QryString = strQry

End Function
Maybe I'm not entering this in the correct spot, I added it after the above code, but I am getting a "compile error, Expected End Sub" after the END WITH at "create query
 
Upvote 0
Please post the entire module you have and is failing (both the main sub and function)
 
Upvote 0
Thank you for your help! Here is the code

VBA Code:
Sub codes()

    ' Select File
    Dim myfile As Variant
    myfile = Application.GetOpenFilename( _
                                          FileFilter:="Text Files (*.lin), *.lin", _
                                          Title:="Select text file", _
                                          ButtonText:="Open")
    If myfile = False Then Exit Sub
    Dim my_workbook As Workbook, my_worksheet As Worksheet
    ' First digit in array is character and 2nd is format.
    Workbooks.OpenText fileName:=myfile, _
        Origin:=437, StartRow:=6, DataType:=xlFixedWidth, FieldInfo:=Array( _
        Array(0, 2), Array(9, 2), Array(13, 2), Array(18, 2)) _
        , TrailingMinusNumbers:=True
    Set my_workbook = ActiveWorkbook
    Set my_worksheet = my_workbook.Sheets(1)

   With my_worksheet
        .Columns("D").EntireColumn.Delete
        Dim rngTbl As Range
        Set rngTbl = Intersect(.Columns("A:C"), .UsedRange)
        Application.CutCopyMode = False
        .ListObjects.Add(xlSrcRange, rngTbl, , xlNo).Name = "Table1"
 
        ' Create Query
        .Parent.Queries.Add Name:="Table1", Formula:=get_QryString
  
    End With
   
      
    Dim second_sheet As Worksheet
    Set second_sheet = my_workbook.Worksheets.Add
  
    With second_sheet.ListObjects.Add(SourceType:=0, Source:= _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=Table1;Extended Properties=""""" _
        , Destination:=second_sheet.Range("$A$1")).QueryTable
        .CommandType = xlCmdSql
        .CommandText = Array("SELECT * FROM [Table1]")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "Table1_2"
         my_workbook.RefreshAll
    End With
  Function get_QryString() As String

    Dim strQry As String
  
    strQry = "let"
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "Source = Excel.CurrentWorkbook(){[Name=""Table1""]}[Content],"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", type text}, {""Column2"", type text}, {""Column3"", type text}}),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows"" = Table.SelectRows(#""Changed Type"", each [Column2] <> null and [Column2] <> """"),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows1"" = Table.SelectRows(#""Filtered Rows"", each not Text.StartsWith([Column2], ""8"")),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows2"" = Table.SelectRows(#""Filtered Rows1"", each not Text.StartsWith([Column2], ""9"")),"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows3"" = Table.SelectRows(#""Filtered Rows2"", each ([Column2] <> ""-05"" and [Column2] <> ""H IN"" and [Column2] <> ""NBR""))"
  
    strQry = strQry & Chr(13) & "" & Chr(10)
    strQry = strQry & "in"
  
    strQry = strQry & Chr(13) & "" & Chr(10) & String(4, " ")
    strQry = strQry & "#""Filtered Rows3"""
  
    get_QryString = strQry

End Function
   ' Copy and Paste_into_new_sheet
    Dim lastRow As Long, CopyRange As Range
    Dim PasteWorkbook As Workbook, PasteSheet As Worksheet, PasteRange As Range
    With second_sheet
        lastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        Set CopyRange = .Range(.Cells(2, 1), .Cells(lastRow, 3))
    End With
  
    MsgBox "LastRow: " & lastRow & ", and CopyRange: " & CopyRange.Address
    Set PasteWorkbook = Workbooks.Open(fileName:= _
        "https://company-my.sharepoint.com/personal/myname_company_com/Documents/Desktop/file2.xlsm")
    'Set PasteWorkbook = Workbooks.Add ' For testing
    Set PasteSheet = PasteWorkbook.Sheets(1) ' YOU MIGHT NEED TO CHANGE THIS
    CopyRange.copy Destination:=PasteSheet.Range("A5")
 

End Function
End Sub
 
Upvote 0
4 separate SelectRows statements seems a little overkill? ;)
 
Upvote 0

Forum statistics

Threads
1,221,310
Messages
6,159,176
Members
451,543
Latest member
cesymcox

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top