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
 
Copy the code below and replace what you have entirely.
I haven't addressed Rory's point, let's just getting it working first, if you wanted to combine some of the select / filtering statements we could do that.

Rich (BB 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

   ' 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



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
Solution

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
SUCCESS! THANK YOU SO MUCH!!

AH! I did put the function in the incorrect place also! Thats pretty new to me.

This worked great!
 
Upvote 0

Forum statistics

Threads
1,223,884
Messages
6,175,174
Members
452,615
Latest member
bogeys2birdies

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