首页 > 解决方案 > 在 Excel VBA 中暂停循环,直到另一个 Sub 完成

问题描述

我正在尝试编写一个宏来实现以下目标:

我已经完成了前两个步骤,但我找不到循环它的方法,以便它下载其余的符号。似乎我所有的循环尝试都是:

只要我没有 For ... Next i 循环,我的代码就可以正常工作,但是一旦我添加它就会导航到该站点,但是当提示打开 CSV 文件时它不会被打开。

下面是我的代码的简化示例。我导航到 Google 以模拟登录步骤(应该只发生一次)。然后我导航到 CSV 的实际地址,然后调用 MoveIt Sub 将其放置在我想要的位置。

因为它工作正常,但是当我添加 For...Loop (当前在代码中标记为注释)时,它会停止打开文件。

我还在第一个 Sub 中尝试了 Do.While 循环(也标记为注释),以便在第二个 Sub 完成之前它不会做任何事情,但它也不起作用。

Public i As Integer, j As Integer

Sub GetHistoricalCSV()

Dim ieApp As InternetExplorer
Dim web As String

i = 1


Set ieApp = New InternetExplorer 'create a new instance of ie
ieApp.Visible = True

ieApp.Navigate "https://google.com" 'go to login page
    Do While ieApp.Busy: DoEvents: Loop
    Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop

'For i = 1 To 3 'This is the start of the loop

j = 0

web = "http://www.global-view.com/forex-trading-tools/forex-history/exchange_csv_report.html?CLOSE_" & i & "=ON&start_date=09/16/2018&stop_date=09/16/2018&Submit=Get Daily Stats"

ieApp.Navigate web

    'Wait to make sure IE has navigated and is prompting to open or save the CSV
    Application.Wait (Now + TimeValue("0:00:03"))
    SendKeys "(%o)" 'Open the CSV


    'I need to wait for the file to open, so I schedule the rest of the code on a new sub
    Application.OnTime Now() + TimeSerial(0, 0, 1), "MoveIt"

'Do Until i = j 'This is telling the code to wait until then next sub has finished
'    DoEvents
'Loop

'Next i 'This is the end of the loop

End Sub

下一个 Sub 将打开的工作表移动到名为“Text.xlsx”的工作簿

Public Sub MoveIt()
Dim Ct As Integer
Ct = 0
For Each wb In Application.Workbooks
    If wb.Name Like "exchange*" Then
        Ct = Ct + 1
        wb.Activate
        Set wbook = ActiveWorkbook
        Exit For
    End If
Next wb

If Ct = 0 Then MsgBox "File not open"

ActiveSheet.Move After:=Workbooks("Test.xlsx").sheets(Workbooks("Test.xlsx").sheets.Count)
ActiveSheet.Name = "Exchange" & i

j = i

End Sub

标签: excelvbaloops

解决方案


您是否考虑过使用 Get & Transform 来解决您的问题?

看起来您可能需要根据日期设置一些参数,但这可以很容易地完成。一段时间以来,我一直在努力寻找解决方案,在reddit上找到了一些帮助,最后在 GitHub 上的这个Workbook中使用以下查询从 iex API 中提取信息。

// If you need more context see the workbook posted above
let
  Parameter = Excel.CurrentWorkbook(){[Name="Parameters"]}[Content],
  URL = Parameter{0}[Value],
  Source = Json.Document(Web.Contents(URL)),
  #"Converted to Table" = Record.ToTable(Source)
in
  #"Converted to Table"

让我知道您是否能够使用它或者您是否需要更多帮助!


推荐阅读