excel - 在 Excel VBA 中暂停循环,直到另一个 Sub 完成
问题描述
我正在尝试编写一个宏来实现以下目标:
- 打开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
解决方案
您是否考虑过使用 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"
让我知道您是否能够使用它或者您是否需要更多帮助!
推荐阅读
- r - 用另一个字符替换数据框中的字符
- reactjs - 刷新页面上的购物车项目丢失
- react-native-android - React native 如何在 expo 中测试后台任务?
- .net - 如果将自签名 SSL 证书添加到 Trusted Root Certification Authorities,是否不需要将证书添加到 WebClient ClientCertificates?
- sql - 如何将列更改为行
- google-workspace - 403 尝试安装 G Suite 市场应用程序时,当我拥有所需的权限时
- python - 制作 bash 文件以显示到终端
- c# - 当我只是尝试从网格视图中获取单元格的值时,我收到有关日期时间的错误
- bash - 在 perl 脚本中捕获 bash 输出值
- r - 列表中的行长度不同