-1

我是 VBA 新手,使用excel 2010 64bit VBA v6.0 compatible。我粘贴了代码,尝试通过 VBA 下载文件。

Option Explicit
'Tutorial link: https://youtu.be/H4-w6ULc_qs
#If VBA7 Then
   Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
     "URLDownloadToFileA" (ByVal pCaller As LongPtr, ByVal szURL As String, ByVal _
       szFileName As String, ByVal dwReserved As LongPtr, ByVal lpfnCB As LongPtr) As LongPtr
#Else
   Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
     "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal _
       szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If

Sub download_file()
'-----------------------------
'Thanks for downloading the code.
'Please visit our channel for a quick explainer on how to use this code.
'Feel free to update the code as per your need and also share with your friends.
'Download free codes from http://vbaa2z.blogspot.com
'Support our channel: youtube.com/vbaa2z
'Author: L Pamai (vbaa2z.team@gmail.com)
'-----------------------------

Dim downloadStatus As Variant
Dim url As String
Dim destinationFile_local As String

url = [D3]
destinationFile_local = "C:\Users\myUserName\Downloads\" & fileName([D3])

downloadStatus = URLDownloadToFile(0, url, destinationFile_local, 0, 0)

If downloadStatus = 0 Then
    MsgBox "Downloaded Succcessfully!"
    Else
    MsgBox "Download failed"
End If

End Sub

Function fileName(file_fullname) As String

    fileName = Mid(file_fullname, InStrRev(file_fullname, "/") + 1)

End Function

但是,弹出窗口说它只能在 64 位系统上运行,如下所示:

编译错误:必须更新此项目中的代码才能在 64 位系统上使用。请查看和更新​​ Declare 语句,然后使用 PtrSafe 属性对其进行标记。


我的问题是:

  1. 我确实使用window 和office 64 位系统。为什么窗口总是弹出?

  2. 有没有办法解决这个问题?

提前致谢。

4

1 回答 1

1

正如错误告诉您的那样,将PtrSafe关键字添加到VBA7分支

#If VBA7 Then
   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 Long
#Else
   Private Declare Function URLDownloadToFile Lib "urlmon" Alias _
     "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal _
       szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If

您需要在使用的任何位置添加此关键字LongPtr,或LongLong

这是关于的 MS 文档PtrSafe

于 2020-07-10T13:30:22.347 回答