尝试删除查询表刷新代码中的选择时遇到的问题

时间:2019-02-20 03:59:03

标签: excel vba

我已经通过使用Excel的Get&Transform(Power Query)经验连接到文本文件,按照给定的代码成功连接到文本文件。 下一个基本文本文件是Axis1.txt,它会定期更改。 接下来,我使用最新数据刷新查询表。 我参考了以下参考资料,以了解有关刷新查询表的信息

How to reference and refresh a QueryTable in Excel 2016 in VBA

Excel VBA / Refresh data from specific source without dialog

https://docs.microsoft.com/en-us/office/vba/api/excel.querytable.refresh

现在是我的问题

在所有引用的方法中,当选择查询表单元格之一并给出以下命令时,我可以使用最新数据刷新表。

Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False

在各种文章中引用的其他类型的代码语法遇到每行提到的错误。

Sub reresh1()
'Sheet2.ListObject.QueryTable.Refresh BackgroundQuery:=False

errorl2

  'Sheets("Sheet2").QueryTables.Refresh BackgroundQuery:=False

errorl3

  Selection.ListObject.QueryTable.Refresh BackgroundQuery:=False
   'WORKS FINE

   End Sub

还尝试了其他各种代码语法组合,但没有成功。

Sub TblImpV1()
' Macro1 Macro
    ActiveWorkbook.Queries.Add Name:="axis1", Formula:= _but 
        "let" & Chr(13) & "" & Chr(10) & "    Source = Csv.Document(File.Contents(""C:\mydirb\axis1.txt""),[Delimiter=""    "", Columns=11, Encoding=1252, QuoteStyle=QuoteStyle.None])," & Chr(13) & "" & Chr(10) & "    #""Changed Type"" = Table.TransformColumnTypes(Source,{{""Column1"", Int64.Type}, {""Column2"", type date}, {""Column3"", type text}, {""Column4"", type text}, {""Column5"", type text}, {""Column6"", type number}, {""C" & _
        "olumn7"", type number}, {""Column8"", type text}, {""Column9"", type text}, {""Column10"", type text}, {""Column11"", type text}})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & "    #""Changed Type"""
    ActiveWorkbook.Worksheets.Add
    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=axis1;Extended Properties=""""" _
        , Destination:=Range("$A$1")).QueryTable
        .CommandType = xlCmdSql
        .CommandText = Array("SELECT * FROM [axis1]")
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .ListObject.DisplayName = "axis1"
        .Refresh BackgroundQuery:=False
    End With
    Range("B4").Select
End Sub

我要避免选择。虽然程序建议去查询表中的任何单元格并按刷新按钮。我相信SO专家在相关问题上的帖子一定是正确的,并且由于我对VBA编码的基本了解,所以我在做一些愚蠢的事情。 欢迎对此事提供任何帮助或指导。希望能使用完整的相关语法而不是一个衬里。

编辑

我可以锻炼解决方案以避免选择。如果B2是查询表中的单元格,则下面的代码行可以正常工作。

Sheets("Sheet2").Range("B2").ListObject.QueryTable.Refresh BackgroundQuery:=False

但是,如果有人有更好的解决方案,那就欢迎您。

0 个答案:

没有答案