0

I am trying to use the function URLDownloadToFile in Access 2010 VBA code. When i run the code it tells me that URLDownloadToFile is not defined.

I have read that this function is in the urlmon.dll which i DO have on my computer. I tried to click the references button in the code editor and load it but it would not let me do so.

How can I fix this so I can use the function? Or is there another function that will allow me to download a url to to a file?

danjfoley
  • 778
  • 1
  • 8
  • 20

1 Answers1

2

You'll need to declare this WinAPI function in order to call it from procedures in your code.

From HERE

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

Public Function DownloadFile(URL As String, LocalFilename As String) As Boolean
Dim lngRetVal As Long
lngRetVal = URLDownloadToFile(0, URL, LocalFilename, 0, 0)
If lngRetVal = 0 Then 
    If Dir(LocalFileName) <> vbNullString Then 
        DownloadFile = True
    End If
End If
End Function

Private Sub Form_Load()
If Not DownloadFile("http://www.ex-designz.net", "c:\\photogallery.asp") Then
    MsgBox "Unable to download the file, or the source URL doesn't exist."
End If
End Sub
David Zemens
  • 53,033
  • 11
  • 81
  • 130
  • This works! Thanks.. However, it seems that the URLDownloadToFile function will report sucess even if the url doesn't exist! How can I put some check in there, or get it to give me an non successful result if it didn't download anything. – danjfoley Oct 03 '14 at 20:43
  • It seems backwards to me that a function woudl report success if it didn't download anything because the url didn't exist. – danjfoley Oct 03 '14 at 20:43
  • You'll have to add another check to see if the destination file (`LocalFileName`) exists. I'll make a quick revision, but if this has answered your question, please consider upvoting it or accepting it. – David Zemens Oct 03 '14 at 20:47
  • There are other ways you could handle tihs of course, first by querying the URL *before* passing it to the function, etc. Above is basically a hack -- it can't determine whether the URL is invalid, it only attempts tod etermine whether there exists a file at the specified `LocalFileName` path. – David Zemens Oct 03 '14 at 20:50