2016-05-15 38 views
0

我正在寫一個腳本來找到基於股票名稱的代號。當然,有時候公司並不是他們寫作的方式。其原因通常來源於最後的一些無關緊要的東西。我試圖寫我的腳本,以便它會重複刪除單詞,直到收到代碼。如果股票從未獲得,則繼續下一步並選擇下一行。有沒有辦法做到這一點?重複任務,直到沒有更多的錯誤vba

Sub TickerLookup() 

cell = ActiveCell.Value 

10 If Not IsEmpty(ActiveCell.Value) Then 
    GoTo GetTicker 
    Else 
    GoTo 20 
End If 
Catch: 
    For Each c In Selection 
     If Not IsEmpty(c.Offset(, -1)) Then 
      cell = Left(cell, InStrRev(cell, " ") - 1) 
      MsgBox cell 
     Else 
      MsgBox "Please clear all adjacent cells" 
     End If 
Next 
Resume Next 
Selection.Offset(1, 0).Select 
GoTo 10 

GetTicker: 

    cell = ActiveCell.Value 
    'remInc = Replace(cell, "INC", "") 
    'remCos = Replace(remInc, "COS", "") 
    cmpnyName = cell 

    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) 


    On Error GoTo Catch 
    ActiveCell.Offset(, -1).Value = Json(1)("Symbol") 

    Selection.Offset(1, 0).Select 
    GoTo 10 

20 End Sub 
+2

'Goto' ??真?這就是soooo八十年代...... – trincot

+0

你只需要測試'Err'對象,然後採取相應的行動,雖然這看起來像是一個XY問題 - 我敢打賭有一個更好的方式來測試你的數據。 –

回答

0

對於您所描述的問題(循環,直到錯誤消失)的解決方案是:

Do 
    On Error Resume Next 'reset Err.obj. 
    'do things you want here 
    If (BoolExpressionYoWantIsTrue) Then 'the test you mention: the string is OK 
     'do what you want 
     Exit Do 'quit loop 
    End If 
Loop Until (Err.Number = 0) 
On Error Goto 0 'turn off error sinking 

此外,使用「轉到」表達嘗試代碼,而無需不斷。例如,您可以添加Exit Sub來代替那個「轉到20」。

相關問題