根据输入值使用Query.Add过滤行

时间:2018-08-14 08:41:27

标签: excel vba filter row

我有以下用于导入csv文件的代码。导入时我总是只希望列号2,3&4。在代码中工作正常。但我也想根据用户输入(xObjID)来过滤行。目前,该代码仅过滤值“ 140”。请帮助我在导入期间根据用户输入的值xObjID过滤行,即在“每个([Object ID] = 140))”部分而不是140中要使用xObjID

    Sub Import_Trends()
    '
    ' Import_Trends Macro
    '

    '
        Dim xFileName As Variant
        Dim xObjID As Variant

        xFileName = Application.GetOpenFilename("CSV File (*.csv), *.csv", , "Browse the File S2KVTQ_VTQTimeTable.csv", , False)
        If xFileName = False Then Exit Sub
        On Error Resume Next

        xObjID = InputBox("Enter Object ID")

        MsgBox "Please wait while the data is loaded", , "PLEASE WAIT..."

Sheets("Trends").Select
        Range("A1").Select
        ActiveWorkbook.Queries.Add Name:="S2KVTQ_VTQTimeTable", Formula:= _
            "let" & Chr(13) & "" & Chr(10) & "    Source = Csv.Document(File.Contents(""" & xFileName & """),[Delimiter="","", Columns=6, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", Int64.Type}, {""Column2"", Int64.Type}, {""Column3"", type number}, {""Column4"", type datetime}, {""Column5"", type nu" & _
            "mber}, {""Column6"", Int64.Type}})," & Chr(13) & "" & Chr(10) & "    #""Removed Other Columns"" = Table.SelectColumns(#""Changed Type"",{""Column2"", ""Column3"", ""Column4""})," & Chr(13) & "" & Chr(10) & "    #""Renamed Columns"" = Table.RenameColumns(#""Removed Other Columns"",{{""Column2"", ""Object ID""}, {""Column3"", ""Value""}, {""Column4"", ""Date & Time""}})," & Chr(13) & "" & Chr(10) & "    #""Filtered Rows"" = Table.SelectRows(#""Rename" & _
            "d Columns"", each ([Object ID] = 140))" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Filtered Rows"""
        With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
            "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=S2KVTQ_VTQTimeTable;Extended Properties=""""" _
            , Destination:=Range("$A$1")).QueryTable
            .CommandType = xlCmdSql
            .CommandText = Array("SELECT * FROM [S2KVTQ_VTQTimeTable]")
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .BackgroundQuery = True
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .PreserveColumnInfo = True
            .ListObject.DisplayName = "S2KVTQ_VTQTimeTable_1"
            .Refresh BackgroundQuery:=False
        End With
    End Sub

0 个答案:

没有答案