我正在编写Excel宏来查找公司名称并返回自动收报机。可以想象,有时数据库找不到公司名称的匹配项。当发生这种情况时,我希望它转到我的代码的Catch:部分,然后继续下一个单元格。是否可以按照我编写代码的方式执行此操作?
Sub TickerLookup()
StartFunction:
For Each c In Selection
On Error GoTo Catch
cell = c.Value
remCo = Replace(cell, "CO", "")
remCos = Replace(remCo, "COS", "")
remNew = Replace(remCos, "NEW", "")
cmpnyName = Replace(remNew, "INTL", "")
ticker = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=" & cmpnyName
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", ticker
MyRequest.Send
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.ResponseText)
'Set the cell to the left as ticker
c.Offset(, -1).Value = Json(1)("Symbol")
Next
Exit Sub
Catch:
FirstName = Trim$(Left$(cell, InStr(cell, " ") - 1))
MsgBox "Now trying: " & FirstName
ticker2 = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=" & FirstName
MyRequest.Open "GET", ticker2
MyRequest.Send
Set Json = JsonConverter.ParseJson(MyRequest.ResponseText)
c.Offset(, -1).Value = Json(1)("Symbol")
GoTo StartFunction
End Sub
答案 0 :(得分:0)
您是否可以在每个的之外移动错误?然后将 next 移动到catch处理程序?
答案 1 :(得分:0)
以下代码修改将所有处理放在循环中。它进一步将错误捕获移动到您发现错误的部分(在您的代码中,每个错误都被捕获,即使您不知道如何处理,例如格式错误的http请求):
Sub TickerLookup()
For Each c In Selection
cell = c.Value
remCo = Replace(cell, "CO", "")
remCos = Replace(remCo, "COS", "")
remNew = Replace(remCos, "NEW", "")
cmpnyName = Replace(remNew, "INTL", "")
ticker = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=" & cmpnyName
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", ticker
MyRequest.Send
On Error GoTo Catch
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.ResponseText)
On Error GoTo 0
'Set the cell to the left as ticker
c.Offset(, -1).Value = Json(1)("Symbol")
GoTo CatchContinue
Catch:
On Error GoTo 0
FirstName = Trim$(Left$(cell, InStr(cell, " ") - 1))
MsgBox "Now trying: " & FirstName
ticker2 = "http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=" & FirstName
MyRequest.Open "GET", ticker2
MyRequest.Send
On error GoTo Catch2
Set Json = JsonConverter.ParseJson(MyRequest.ResponseText)
c.Offset(, -1).Value = Json(1)("Symbol")
Catch2:
On Error GoTo 0
CatchContinue:
Next
End Sub