50290 Runtime Error - Almost Wasted Effort

nØthing spec¡al by Jimsjoo·2024년 3월 26일
0

VBA

목록 보기
3/13


I'm using a stock broker's API to retrieve and backtest technical indicators, and I'm getting a 50290 runtime error. It works fine when searching for a single stock, but when searching for multiple stocks at once, the VBA throws a '50290 runtime error' when the callback function is executed on the last stock search.

This is an old error that occurs when Excel is running in the background.

Private Sub btnQuery_Click()
  Dim rng As Range
  Dim szSym As String
  
  For Each rng In [B23:B30]
    If GetQueueStatus(QS_INPUT) <> 0 Then DoEvents
    szSym = rng.Value
    Set rngWrite = rng.Offset(0, 2)
    Debug.Print rngWrite.Address
    Call reqChartIndex(szSym)
    Call API.Halt(3)
'    Application.Wait (Now + TimeValue("0:00:03"))
  Next
  
End Sub
...
...
...
Private Sub xaQ_ReceiveData(ByVal szTrCode As String)
  Dim i As Long, j As Long, cnt As Long
  Dim szFld As String
  Dim fldsChartIndex

  ' 지표의indexid (지표별 구분키로 사용할 수 있다)
  g_indexId = xaQ.GetFieldData("ChartIndexOutBlock", "indexid", 0)
  ' 데이터 갯수
  cnt = xaQ.GetFieldData("ChartIndexOutBlock", "rec_cnt", 0):  If cnt = 0 Then Exit Sub
  cnt = cnt - 1
' 최근일자의 OHLCV와 지표 출력
  fldsChartIndex = Array("date", "open", "high", "low", _
    "close", "volume", "value1", "value2")
  ReDim OHLC(UBound(fldsChartIndex))
  For j = LBound(fldsChartIndex) To UBound(fldsChartIndex)
    szFld = fldsChartIndex(j)
    OHLC(j) = xaQ.GetFieldData("ChartIndexOutBlock1", szFld, cnt)
  Next
  Me.Range(rngWrite, rngWrite.Offset(0, 7)) = OHLC
End Sub
...
...
...
Public Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long

Sub Halt(Finish As Long)
'Finish in seconds
  Dim NowTick As Long
  Dim EndTick As Long
  EndTick = GetTickCount + (Finish * 1000)
  Do
      NowTick = GetTickCount
      DoEvents
  Loop Until NowTick >= EndTick
End Sub

In particular, I got a runtime error for Me.Range(rngWrite, rngWrite.Offset(0, 7)) = OHLC, and at first I suspected that the Range object to output was Nothing.

However, both the Range and the OHLC array were fine. Fortunately Stackoverflow (Run-time error '50290': Application-defined or object-defined error when Excel runs in the background) had the answer. Of course, the questioner's error was caused by using asynchronous WinHTTP, but what he and I have in common is that the error is caused by running Excel in the background. It seems that calling the Application while it is running in the background is the cause of the problem.

When I first created the callback function, I gave it about 3 seconds to Wait like this,
Application.Wait (Now + TimeValue("0:00:03"))

I changed it to the API function GetTickCount as per Sergei Trunov's answer and it seems to work fine.

profile
harmonized or torn between programming and finance

0개의 댓글