使用VBA从网页批量下载Excel文件的实现方案求助
VBA批量下载akk.hu零息收益率Excel文件(按7天步长遍历整年)
实现步骤说明
- 日期区间拆分:从指定起始日期到结束日期,按7天步长拆分区间,最后一段自动适配剩余天数
- 页面元素定位:通过浏览器开发者工具(F12)确认日期输入框与下载按钮的HTML标识
- 自动化流程:启动IE加载页面→填充日期区间→触发数据查询→点击下载→等待文件保存→进入下一个区间
完整VBA代码
Sub DownloadZeroCouponYields() Dim ie As InternetExplorer Dim doc As HTMLDocument Dim startDate As Date, endDate As Date Dim currentFrom As Date, currentTo As Date Dim waitTime As Integer Dim fromInput As Object, toInput As Object, downloadBtn As Object ' 配置参数 startDate = DateSerial(2023, 1, 1) ' 起始年份 endDate = DateSerial(2023, 12, 31) ' 结束年份 waitTime = 3 ' 页面加载等待时间(秒) Set ie = New InternetExplorer With ie .Visible = True ' 调试时设为True,正式运行可设为False .Navigate "https://akk.hu/statistics/yields-indices-market-turnover/zero-coupon-yields" ' 等待页面加载完成 Do While .Busy Or .ReadyState <> READYSTATE_COMPLETE DoEvents Loop Set doc = .Document currentFrom = startDate Do While currentFrom <= endDate ' 计算当前区间结束日期,不超过全年结束日期 currentTo = DateAdd("d", 6, currentFrom) If currentTo > endDate Then currentTo = endDate ' 定位日期输入框(需根据实际页面HTML调整ID) On Error Resume Next Set fromInput = doc.getElementById("fromDate") Set toInput = doc.getElementById("toDate") On Error GoTo 0 If Not fromInput Is Nothing And Not toInput Is Nothing Then ' 填充日期(格式需匹配网站要求,示例为yyyy-MM-dd) fromInput.Value = Format(currentFrom, "yyyy-MM-dd") toInput.Value = Format(currentTo, "yyyy-MM-dd") ' 触发日期变更后的查询(部分网站需点击刷新按钮,若无需则注释) ' doc.getElementById("refreshButton").Click ' Application.Wait Now + TimeValue("00:00:" & waitTime) ' 定位并点击Excel下载按钮 On Error Resume Next Set downloadBtn = doc.querySelector("button[title='Export to Excel'], a.export-excel") On Error GoTo 0 If Not downloadBtn Is Nothing Then downloadBtn.Click ' 等待下载弹窗处理(可提前设置IE默认下载路径避免弹窗) Application.Wait Now + TimeValue("00:00:" & waitTime) ' 若需自动确认下载,可添加SendKeys(仅临时方案,不稳定) ' SendKeys "%{S}", True Else MsgBox "未找到Excel下载按钮,请检查页面HTML结构" Exit Sub End If Else MsgBox "未找到日期输入框,请检查页面HTML结构" Exit Sub End If ' 移动到下一个7天区间 currentFrom = DateAdd("d", 7, currentFrom) Loop ' 关闭IE .Quit End With Set ie = Nothing MsgBox "所有文件下载完成" End Sub
关键注意事项
- 引用库配置:打开VBA编辑器→工具→引用→勾选「Microsoft Internet Controls」和「Microsoft HTML Object Library」
- HTML元素适配:若代码中元素ID/选择器无效,按以下步骤确认:
- 打开目标页面,按F12打开开发者工具
- 用「选择元素」工具点击日期输入框/下载按钮
- 在Elements面板中复制元素的
id属性或编写合适的CSS选择器替换代码中的对应部分
- 下载路径设置:打开IE→设置→查看高级设置→下载→设置默认下载位置,避免每次手动选择路径
- 稳定性优化:若页面加载慢,可增大
waitTime参数;若遇到弹窗拦截,需确保IE允许该网站的弹出窗口
内容的提问来源于stack exchange,提问作者Olivér Gács
相关产品推荐
相关产品推荐

