Search code examples
excelvbavba6vba7

Troubled with VBA version difference: version 6 and version 7


I'm new to VBA and use excel 2010 64bit VBA v6.0 compatible. I pasted the code, trying to download files through 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

However, a pop-up window says it can only run on 64-bit systems as follow:

Compile error: The code in this project must be updated for use on 64-bit systems. Please review and update Declare statements and then mark them with the PtrSafe attribute.


My questions are:

  1. I do use window and office 64-bit system. Why the window keeps popping up?

  2. Is there any way to solve this problem?

Thanks in advance.


Solution

  • As the error tells you, add the PtrSafe keyword to the VBA7 branch

    #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
    

    You need to add this keyword anywhere you are using LongPtr, or LongLong.

    Here is the MS Documentation on PtrSafe