包含变量的 Excel 2013 VBA Web 查询连接字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21152991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 01:25:00  来源:igfitidea点击:

Excel 2013 VBA Web Query connection string containing variable

vbaexcel-vbaexcel-2013excel-web-queryexcel

提问by user3200885

I am getting a Run-time error'1004' error on the following line.

我在以下行中收到运行时错误“1004”错误。

With ActiveSheet.QueryTables.add(Connection:=connstring, Destination:=Range("$b"))
Destination:=Range("$b"))

The Variable connstring seems to be causing the problem. How do I properly use the variable name in this connection statement?

变量 connstring 似乎是导致问题的原因。如何正确使用此连接语句中的变量名称?

Help would be greatly appreciated

帮助将不胜感激



Sub add()

For x = 1 To 58000

 Worksheets("PAGES").Select
 Worksheets("PAGES").Activate

 connstring = "http://www.name-list.net/russia/1"

 With ActiveSheet.QueryTables.add(Connection:=connstring, Destination:=Range("$b"))
 Destination:=Range("$b"))

    .Name = "1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .WebSelectionType = xlSpecifiedTables
    .WebFormatting = xlWebFormattingNone
    .WebTables = "2"
    .WebPreFormattedTextToColumns = True
    .WebConsecutiveDelimitersAsOne = True
    .WebSingleBlockTextImport = False
    .WebDisableDateRecognition = False
    .WebDisableRedirections = False
    .Refresh BackgroundQuery:=False
End With

Next x

回答by robnick

Change connstring to be -->

将连接字符串更改为 -->

connstring = "URL;http://www.name-list.net/russia/1"

Better still -->

还是更好 -->

Dim connstring As String
connstring = "URL;http://www.name-list.net/russia/1"

The MSDN doco for that method is QueryTables.Add Method

该方法的 MSDN doco 是QueryTables.Add Method

I can't guarantee the rest of your code will work as you expect. Why are you looping 58000 times?

我不能保证您的其余代码会按您的预期工作。为什么要循环 58000 次?