从工作簿中的单元格自动更新 strURL 字符串

问题描述 投票:0回答:1

我每个月都从统计网站下载 zip 文件。我有一个 excel vba 宏,可以为我下载文件,但位置每个月都会更改。 例如。最新数据可在 strURL = "https://www.statistics/retail-trade/Jan-2023/Time-Series.zip" 但下个月会 strURL = "https://www.statistics/retail-trade/feb-2023/Time-Series.zip"

如果可能的话,我希望宏从工作簿中的单元格中获取新地址,这样我就可以简单地更新单个单元格日期值,而不是每个月在宏中编写代码

下面是我正在使用的宏

Sub DownloadRetailTrade()
Dim strURL As String
Dim LocalFilePath As String
Dim DownloadStatus As Long



strURL = "https://www.statistics/retail-trade/Jan-2023/Time-Series.zip"

LocalFilePath = "D:\Data\Time-Series.zip"
DownloadStatus = URLDownloadToFile(0, strURL, LocalFilePath, 0, 0)
If DownloadStatus = 0 Then
    MsgBox "File Downloaded. Check in this path: " & LocalFilePath
Else
    MsgBox "Download File Process Failed"
End If
Call UnZipMe
End Sub

我的工作簿中有一个连接函数,可以在我更新日期时创建新的 URL。我只是无法弄清楚如何让我的代码每个月都获取新的 URL。 目前我进入代码并更改它。我相信一定有更好的方法。

excel vba download zip auto-update
1个回答
0
投票

如果你的区域设置是英文的,你可以这样做:

strURL = "https://www.statistics/retail-trade/" & Format(Date, "mmm") & "-2023/Time-Series.zip"

这将从今天的日期获取当前月份的名称并将其添加到字符串中。所以如果你今天执行,它会返回:

https://www.statistics/retail-trade/mar-2023/Time-Series.zip

在 2024 年它会改变,所以正确的解决方案是:

strURL = "https://www.statistics/retail-trade/" & Format(Date, "mmm-yyyy") & "/Time-Series.zip"

如果你没有英文设置并且你的月份名称不同(例如我的是西班牙语),上面的代码将不起作用!你需要计算月份然后得到英文的首字母:

Dim MonthArray As Variant

MonthArray = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")

strURL = "https://www.statistics/retail-trade/" & MonthArray(Month(Date) - 1) & Format(Date, "-yyyy") & "/Time-Series.zip"

请注意我在代码中使用了

Date
但这可以替换为您想要的任何日期(单元格或其他)。

© www.soinside.com 2019 - 2024. All rights reserved.