编写Excel VBA脚本:按日期范围搜索并下载对应文件
按日期范围批量下载文件的Excel VBA实现
核心思路
将日期变量改为Date类型以便遍历,通过循环逐个生成每日文件的URL,调用Windows API完成下载,同时处理目标文件夹不存在的情况,避免报错。
完整代码
' 声明用于下载文件的Windows API(兼容32/64位Excel) Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _ Alias "URLDownloadToFileA" (ByVal pCaller As LongPtr, _ ByVal szURL As String, ByVal szFileName As String, _ ByVal dwReserved As Long, ByVal lpfnCB As LongPtr) As LongPtr Sub Get_XY() Dim dtReportDateStart As Date Dim dtReportDateEnd As Date Dim currentDate As Date Dim strPricesLocation As String Dim strPricesDestination As String Dim baseURL As String Dim saveFolder As String ' 替换为实际文件的URL前缀 baseURL = "http://your-file-server/path/" ' 替换为本地保存文件的目标文件夹 saveFolder = "C:\Local-Save-Path\XY_Files\" ' 从Dashboard工作表读取起始、结束日期 dtReportDateStart = ThisWorkbook.Worksheets("Dashboard").Range("C2").Value dtReportDateEnd = ThisWorkbook.Worksheets("Dashboard").Range("C3").Value ' 检查目标文件夹是否存在,不存在则创建 If Dir(saveFolder, vbDirectory) = "" Then MkDir saveFolder End If ' 循环遍历日期范围内的每一天 currentDate = dtReportDateStart Do While currentDate <= dtReportDateEnd ' 生成当日文件的完整URL strPricesLocation = baseURL & Format(currentDate, "YYYYMMDD") & ".tsv.txt" ' 生成本地文件的保存路径 strPricesDestination = saveFolder & Format(currentDate, "YYYYMMDD") & ".tsv.txt" ' 执行下载并反馈结果 If URLDownloadToFile(0, strPricesLocation, strPricesDestination, 0, 0) = 0 Then Debug.Print "下载成功: " & strPricesDestination Else Debug.Print "下载失败: " & strPricesLocation End If ' 日期递增1天 currentDate = DateAdd("d", 1, currentDate) Loop End Sub
关键细节说明
- 变量类型优化:用
Date类型存储日期,避免字符串格式冲突,方便通过DateAdd快速递增日期。 - API下载优势:
URLDownloadToFile是系统级API,比手动模拟浏览器下载更稳定高效。 - 容错处理:提前创建目标文件夹,防止因路径不存在导致下载中断。
- 结果反馈:通过
Debug.Print输出下载状态,便于排查失败的文件。
使用注意事项
- 替换代码中的
baseURL为实际文件的URL前缀。 - 替换
saveFolder为你指定的本地保存路径。 - 若文件需要身份验证,需额外添加HTTP请求头的认证逻辑。
- 确保Excel启用了宏功能,且信任该VBA项目。
内容的提问来源于stack exchange,提问作者Michael W
相关产品推荐
相关产品推荐

