在Excel VBA中暂停循环,直到另一个Sub完成

时间:2018-09-15 21:36:42

标签: excel vba loops

我正在尝试编写宏以实现以下目的:

  • 打开IE,然后登录金融网站
  • 打开符号历史价格的CSV文件并将其移至另一工作簿
  • 重复步骤2的几个符号

我已经完成了前两个步骤,但是我找不到一种循环的方式,因此它无法下载其余符号。似乎我所有尝试循环的尝试之一:

  • 运行循环太快
  • 由于某种原因,我的代码无法像以前一样工作。

只要我没有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

2 个答案:

答案 0 :(得分:0)

由于您没有选择要启动下载的元素,因此应该可以使用构造的url直接尝试二进制文件下载/ urlmon下载。前提是您已经在代码中更早地登录,则sessionid / cookie有望在适当的位置仍然有效。使用下载功能返回下载完整路径,并收集这些功能以供以后打开下载的文件。

答案 1 :(得分:0)

您是否考虑过使用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"

让我知道您是否可以使用此功能,或者是否需要更多帮助!