我有一个很长的URL列表,我从中循环并解析JSON文本。 URL列表太长了,我的结构如下(urlArray = Array("URL1", "URL2", "URL3", "URL4", "URL5"
),因为URL最终分成两行,我收到的错误只能通过将URL列表数组缩短回一行(长码)。 (注意:如果您认为我可以修复此原始结构/语法,请告诉我,因为它适用于< 7个网址)
我将我的网址数组更改为以下格式(仅替换上面提到的urlArray = Array("URL1", "URL2", "URL3", "URL4", "URL5"
,见下文):
urlArray(1) = "URL1"
urlArray(2) = "URL2"
urlArray(3) = "URL3"
urlArray(4) = "URL4"
urlArray(5) = "URL5"
当我更改为这种新格式时,我收到运行时错误' 5':
无效的过程调用或参数
突出显示.Open "GET", MyUrls(k)
所以,我的问题是,我可以将格式更改为这个新结构吗?或者,考虑到我的情况,我应该向另一个方向走(很长的URL列表似乎不能以第一种格式工作)?
完整代码预更改:
Option Explicit
Sub getJSON()
Dim sheetCount As Integer, urlArray As Variant
sheetCount = 1
urlArray = Array("URL1", "URL2", "URL3", "URL4", "URL5", "etc.")
Dim MyRequest As Object: Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim MyUrls: MyUrls = urlArray
Dim k As Long
Dim Json As Object
For k = LBound(MyUrls) To UBound(MyUrls)
With MyRequest
.Open "GET", MyUrls(k)
.Send
Set Json = JsonConverter.ParseJson(.ResponseText)
Dim i As Long, p As Object
For i = 1 To Json("prices").Count
Set p = Json("prices")(i)
Sheets("Sheet" & sheetCount).Cells(i, 1) = p("name")
Sheets("Sheet" & sheetCount).Cells(i, 2) = p("cost")("fareType")
Sheets("Sheet" & sheetCount).Cells(i, 9) = p("cost")("base")
Sheets("Sheet" & sheetCount).Cells(i, 10) = p("cost")("perMinute")
Next i
End With
sheetCount = sheetCount + 1
Next k
End Sub
答案 0 :(得分:1)
下划线_
允许您将代码继续到下一行。
Sub getJSON()
Dim sheetCount As Integer, urlArray As Variant
sheetCount = 1
urlArray = Array("URL1", "URL2", "URL3", "URL4", "URL5", "URL6", "URL7", _
"URL8", "URL9", "URL10", "URL11", "URL12", "URL13", "URL14", _
"URL15", "URL16", "URL17", "URL18", "URL19", "URL20")
Dim MyRequest As Object: Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim MyUrls: MyUrls = urlArray
Dim k As Long
Dim Json As Object
For k = LBound(MyUrls) To UBound(MyUrls)
With MyRequest
.Open "GET", MyUrls(k)
.Send
Set Json = JsonConverter.ParseJson(.ResponseText)
Dim i As Long, p As Object
For i = 1 To Json("prices").Count
Set p = Json("prices")(i)
Sheets("Sheet" & sheetCount).Cells(i, 1) = p("name")
Sheets("Sheet" & sheetCount).Cells(i, 2) = p("cost")("fareType")
Sheets("Sheet" & sheetCount).Cells(i, 9) = p("cost")("base")
Sheets("Sheet" & sheetCount).Cells(i, 10) = p("cost")("perMinute")
Next i
End With
sheetCount = sheetCount + 1
Next k
End Sub
您可能希望使用For Each
循环遍历数组。
Dim k As Variant
For k = LBound(MyUrls) To UBound(MyUrls)
With MyRequest
.Open "GET", k
我会将Urls存储在电子表格中:
您可以将它们加载到数组中:
Dim MyUrls
With Worksheets("Sheet1")
MyUrls = .Range("A2", .Range("A" & .Rows.Count).End(xlUp)).Value
End With