Open a page in a pdf using VBA in Excel - excel

I am working to open a specific page of a pdf using VBA in Excel.
Sub CommandButton1_Click()
Dim p As Long, i As Long
'there is a space after exe
ExeFilepath = "C:\Program Files (x86)\Adobe\Acrobat Reader 2015\Reader\AcroRd32.exe "
Filepath = "\\ch3ww0001\fold1\sample.pdf"
Filename = "sample.pdf"
p = Shell(ExeFilepath & Filepath, vbNormalFocus)
another try:
'p = Shell(ExeFilepath + "/A ""page=1"" " + Filepath, vbNormalFocus)
SendKeys "%DG" & [D148] & "+{ENTER}"
For i = 1 To 10 ^ 4
DoEvents
Next
'AppActivate p, True
SendKeys "%DG" & [D148] & "+{ENTER}"
End Sub
I want to link different pages in a pdf document. Those pages are listed in cells from D148 to D160.
I want to click different cells of D148-D160 to open the page in the sample.pdf.

After trying for many times I found the right way to do this:
using the below shell command can fix this problem.
But, we have to notice is that:
The pdf file must be stored in your local Disk!! A web location can not really work.
p = Shell(ExeFilepath + "/A ""page=1"" " + Filepath, vbNormalFocus)
Here is the complete code:
Sub PDF_Link(ByVal target As Range)
Dim p As Long, i As Long
ExeFilepath = "C:\Program Files (x86)\Adobe\Acrobat Reader 2015\Reader\AcroRd32.exe /A ""page="
Filepathname = "C:\Work\example.pdf"
p = Shell(ExeFilepath & target + 2 & """ " & Filepathname, vbMaximizedFocus)
End Sub
In the code above "target" is the destiny page I want to open.

I find another method to do this and verified this is ok!
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Const SW_SHOWMAXIMIZED = 3 '最大化显示参数
Const SW_SHOWMINIMIZED = 2 '最小化显示参数
Const SW_SHOWNORMAL = 1 '正常显示参数
Const SW_HIDE = 0
Public Sub openPDFPage(ByVal myPage As Long)
Dim myLink As String
'Dim myPage As Long
Dim objIE As New InternetExplorer
myLink = "C:\Work\exapmle.pdf"
'myLink = "http://www.excelvbatutor.com/vba_book/vbabook_ed2.pdf"
'myPage = InputBox("Enter the page number")
With objIE
.Navigate myLink & "#page=" & myPage
.Visible = True
.Silent = False
End With
ShowWindow objIE.hwnd, SW_SHOWMAXIMIZED
End Sub

Related

How to bring network_delegate to StdErr in wshell or vba?

If I run chrome from CMD I am able to retrieve OAuth2 code, but when I run via VBA / wscript the network_delegate lines which contain the code are absent.
Running this from VBA leaves out network_delegate lines and I have not been able to find a way to bring them in. Pasting chrome & Web_URL into CMD - the lines show up in CMD.
To reproduce: close any open Chrome windows and then close Chrome for sub to end.
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)
Sub chromeLog()
Dim Web_URL As String, chrome As String
Web_URL = """https://www.google.com"""
chrome = """C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"" --profile-directory=""Profile 1"" --enable-logging=stderr --v=1 "
sCmd = Environ$("COMSPEC") & " /s /c """ & chrome & Web_URL & """"
Set wShell = CreateObject("wscript.shell")
Set d = CreateObject("Scripting.Dictionary")
Set wsx = wShell.Exec(sCmd)
Set wsxOut = wsx.StdErr
DoEvents
Do: Sleep 1000
Do Until wsxOut.AtEndOfStream
'If InStr(wsxOut.ReadLine, "network_delegate") > 0 Then
d(d.Count) = wsxOut.ReadLine
'End If
Loop
Loop Until wsx.Status <> 0 And wsxOut.AtEndOfStream
arLines = d.items()
Debug.Print d.Count
For Each iten In d.keys
Debug.Print iten, d(iten)
'Cells(iten + 1, 1).Value2 = d(iten)
Next
Set wShell = Nothing: Set wsx = Nothing: Set wsxOut = Nothing
End Sub

VBA is sometimes not recognizing Excel file that has been opened through SAP GUI script

I have a SAP GUI script running every day in VBA. In the script I am exporting some data from SAP to several different Excel files, and these are saved to a network drive. In the first macro, I export data. In the second I copy the data to the same workbook as the script is in.
Some days I get a runtime error
Subscript out of range
on Set ws2 = Workbooks("FEBA_EXPORT_" & today2 & ".XLSX").Worksheets("Sheet1").
It looks like the Excel file is not recognized as open. I manually close the file, and reopen it and then the script will run.
I tried to insert the below code in front of the Set ws2 line that is giving an error, and this code is always giving the massage that the file is open.
Dim Ret
Ret = IsWorkBookOpen(filepath & "FEBA_EXPORT_" & today2 & ".XLSX")
If Ret = True Then
MsgBox "File is open"
Else
MsgBox "File is Closed"
End If
This is the function:
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
This is the relevant part of the code:
Sub CopyExportedFEBA_ExtractFEBRE()
Dim SapGuiAuto As Object
Dim SAPApp As Object
Dim SAPCon As Object
Dim session As Object
Set SapGuiAuto = GetObject("SAPGUI")
Set SAPApp = SapGuiAuto.GetScriptingEngine
Set SAPCon = SAPApp.Children(0)
Set session = SAPCon.Children.ElementAt(0) ' <--- Assumes you are using the first session open. '
Dim ws0, ws1, ws2, ws6, ws7 As Worksheet
Set ws0 = Workbooks("FEB_BSPROC.xlsm").Worksheets("INPUT")
Set ws1 = Workbooks("FEB_BSPROC.xlsm").Worksheets("FEB_BSPROC")
Set ws6 = Workbooks("FEB_BSPROC.xlsm").Worksheets("FBL3N_1989")
Dim today2, filepath As String
today2 = ws0.Range("E2")
filepath = ws0.Range("A7")
' Check if if FEBA_EXPORT wb is open
' This is giving the message that the file is open
Dim Ret
Ret = IsWorkBookOpen(filepath & "FEBA_EXPORT_" & today2 & ".XLSX")
If Ret = True Then
MsgBox "File is open"
Else
MsgBox "File is Closed"
End If
' This is giving runtime error 9 Subscript out of range
' If manually close the Excel and the reopen, then it will always work after this
Set ws2 = Workbooks("FEBA_EXPORT_" & today2 & ".XLSX").Worksheets("Sheet1")
'This is never giving any errors
Set ws7 = Workbooks("1989_" & today2 & ".XLSX").Worksheets("Sheet1")
The filepath varaiable is the full filepath to the network drive. So this is not the issue. Also I have another Excel file that is opened in the same way, and that one is never giving any errors.
The today2 variable is also correct.
I thought that it would work if I could close the ws2 workbook with VBA and then reopen it. So I tried to close it without setting it to a variable, but then I got the same error.
With SAP GUI scripting when you export anything to an Excel file, the file will open automatically after it has been saved. I am wondering if this could be the issue? I only have problems with this one Excel file, and not with any of several others that are saved and opened in the same way.
As I said in my above comment, the workbook may be open in a new session, different from the one where the code runs. Please, use the next function to identify if it is a matter of different Excel session:
Function sameExSession(wbFullName As String, Optional boolClose As Boolean) As Boolean
Dim sessEx As Object, wb As Object
Set sessEx = GetObject(wbFullName).Application
If sessEx.hwnd = Application.hwnd Then
sameExSession = True
Else
sameExSession = False
If boolClose Then
sessEx.Workbooks(Right(wbFullName, Len(wbFullName) - InStrRev(wbFullName, "\"))).Close False
sessEx.Quit: Set sessEx = Nothing
End If
End If
End Function
It identify the session where the workbook is open, then compare its handle with the active session one and if not the same, close the workbook (if calling the function with second parameter as True), quit the session and returns False. If only checking, call the function with the second parameter being False (the workbook will not be closed, and session will still remain).
It can be used in the next way:
Sub testSameExSession()
Dim wbFullName As String, wbSAP As Workbook
wbFullName = filepath & "FEBA_EXPORT_" & today2 & ".XLSX"
If sameExSession(wbFullName, True) Then
Debug.Print "The same session"
Set wbSAP = Workbooks("FEBA_EXPORT_" & today2 & ".XLSX")
Else
Debug.Print "Different session..."
Set wbSAP = Workbooks.Open(wbFullName)
End If
Debug.Print wbSAP.Name
'use the set workbook to do what you need...
End Sub
When you have the described problem, please use the above way to test if it is a matter of different sessions.
If so, is easy to input this part in your existing code, I think. If the workbook will be open in a different session, no need to manually close it (and reopen), the above function does it...
In case someone is still facing this issue, I found a way to wait for the excel files downloaded from SAP and its app instance to open, then close them and let you work with the files without troubles. You can set a timeout too.
If files are downloaded and opened in an already open instance of excel, it will just close the files and not the whole instance.
You can use it as follow:
Sub Test()
Call Close_SAP_Excel("Test.xlsx", "Test2.xlsx")
End Sub
xCloseExcelFromSAP
#If VBA7 Then
Private Declare PtrSafe Function AccessibleObjectFromWindow Lib "oleacc" ( _
ByVal hwnd As LongPtr, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long
Private Declare PtrSafe Function FindWindowExA Lib "user32" ( _
ByVal hwndParent As LongPtr, ByVal hwndChildAfter As LongPtr, _
ByVal lpszClass As String, ByVal lpszWindow As String) As LongPtr
#Else
Private Declare Function AccessibleObjectFromWindow Lib "oleacc" ( _
ByVal hwnd As Long, ByVal dwId As Long, riid As Any, ppvObject As Object) As Long
Private Declare Function FindWindowExA Lib "user32" ( _
ByVal hwndParent As Long, ByVal hwndChildAfter As Long, _
ByVal lpszClass As String, ByVal lpszWindow As String) As Long
#End If
Sub Close_SAP_Excel(ParamArray FileNames())
'Procedure to close files downloaded from SAP and at the same time close the Excel application instance that will be open with them.
Dim ExcelAppSAP As Variant
Dim ExcelFile As Variant
Dim FinishedLoop As Boolean, TimeoutReached As Boolean, FileClosed As Boolean
Dim ReTry As Long
Dim i As Long, x As Long
Set ExcelAppSAP = Nothing
ReTry = 100000 'Used as Timeout 100000 = ~10 seconds
i = 1
'The following loop is executed until excel file is closed.
'Inside of this, there is a For Loop for each Excel Instance and inside of that is another loop
'for each excel inside the instance. If name matches, it is closed.
Do While Not FinishedLoop
If i > ReTry Then
TimeoutReached = True
Exit Do
End If
For Each ExcelFile In GetExcelInstances() 'Function to Get Excel Open Instances
For Each xls In ExcelFile.Workbooks
For x = LBound(FileNames()) To UBound(FileNames())
If xls.Name = FileNames(x) Then
Set ExcelAppSAP = ExcelFile 'Set Instance opened by SAP to variable
'Here add actions if needed. Reference to workbook as xls e.g.: xls.Sheets(1).Range("A1").Copy
xls.Close SaveChanges:=False
FileClosed = True
End If
Next x
Next
Next
If FileClosed Then
FinishedLoop = True
End If
i = i + 1
Loop
ThisWorkbook.Activate
If Not TimeoutReached Then
If FileClosed Then
On Error Resume Next
If ExcelAppSAP.Workbooks.Count = 0 Then
ExcelAppSAP.Quit
End If
Else
MsgBox "Excel application instance from SAP was not closed correctly. Please close it manually or try again.", , "Error"
End If
Else
MsgBox "Max timeout reached", , "Error"
End If
End Sub
Public Function GetExcelInstances() As Collection
Dim guid&(0 To 3), acc As Object, hwnd, hwnd2, hwnd3
guid(0) = &H20400
guid(1) = &H0
guid(2) = &HC0
guid(3) = &H46000000
Set GetExcelInstances = New Collection
Do
hwnd = FindWindowExA(0, hwnd, "XLMAIN", vbNullString)
If hwnd = 0 Then Exit Do
hwnd2 = FindWindowExA(hwnd, 0, "XLDESK", vbNullString)
hwnd3 = FindWindowExA(hwnd2, 0, "EXCEL7", vbNullString)
If AccessibleObjectFromWindow(hwnd3, &HFFFFFFF0, guid(0), acc) = 0 Then
GetExcelInstances.Add acc.Application
End If
Loop
End Function

Why does Microsoft Barcode Control break when the workbook is opened via interop?

I have a worksheet, to which I have added a QR code.
The QR code is an ActiveX control: Microsoft Barcode Control 14.0
The QR code is linked to a cell (A1), so that when the value in the cell changes, so does the QR code.
When I open the workbook normally, everything works as it should.
However, when I open it using Interop from a vb.net Winforms project, the QR code no longer responds when the value in the linked cell changes.
Whats more, when I right click on the barcode control, the "Microsoft Barcode Control 14.0 Object" context menu option (seen below) is missing.
The interop code that I am using to open the workbook is as follows:
Dim XLApp As New Excel.Application
XLApp.Visible = True
Dim XLBook As Excel.Workbook = XLApp.Workbooks.Open(FilePath)
Can anyone tell me what is causing this to happen? And perhaps suggest what I can do to prevent it happening.
You may call the Calculate method of the Worksheet class each time you need to update the QR code. For example, a raw sketch in VBA:
Application.EnableEvents = True
Application.ScreenUpdating = True
Sheets("QR_CodeSheet").Calculate
I could not get the Microsoft Barcode Control to function correctly with interop.
One way would be to open the file using a shell command and then hook into the process to work with it. But I found this too messy.
Instead, I decided to use google's Chart API. This does require an internet connection. But that is not a problem for me.
Here is a link for more info: https://sites.google.com/site/e90e50fx/home/generate-qrcode-with-excel
And the VBA code:
Option Explicit
'other technical specifications about google chart API:
'https://developers.google.com/chart/infographics/docs/qr_codes
Function URL_QRCode_SERIES( _
ByVal PictureName As String, _
ByVal QR_Value As String, _
Optional ByVal PictureSize As Long = 150, _
Optional ByVal DisplayText As String = "", _
Optional ByVal Updateable As Boolean = True) As Variant
Dim oPic As Shape, oRng As Excel.Range
Dim vLeft As Variant, vTop As Variant
Dim sURL As String
Const sRootURL As String = "https://chart.googleapis.com/chart?"
Const sSizeParameter As String = "chs="
Const sTypeChart As String = "cht=qr"
Const sDataParameter As String = "chl="
Const sJoinCHR As String = "&"
If Updateable = False Then
URL_QRCode_SERIES = "outdated"
Exit Function
End If
Set oRng = Application.Caller.Offset(, 1)
On Error Resume Next
Set oPic = oRng.Parent.Shapes(PictureName)
If Err Then
Err.Clear
vLeft = oRng.Left + 4
vTop = oRng.Top
Else
vLeft = oPic.Left
vTop = oPic.Top
PictureSize = Int(oPic.Width)
oPic.Delete
End If
On Error GoTo 0
If Len(QR_Value) = 0 Then
URL_QRCode_SERIES = CVErr(xlErrValue)
Exit Function
End If
sURL = sRootURL & _
sSizeParameter & PictureSize & "x" & PictureSize & sJoinCHR & _
sTypeChart & sJoinCHR & _
sDataParameter & UTF8_URL_Encode(VBA.Replace(QR_Value, " ", "+"))
Set oPic = oRng.Parent.Shapes.AddPicture(sURL, True, True, vLeft, vTop, PictureSize, PictureSize)
oPic.Name = PictureName
URL_QRCode_SERIES = DisplayText
End Function
Function UTF8_URL_Encode(ByVal sStr As String)
'http://www.nonhostile.com/howto-convert-byte-array-utf8-string-vb6.asp
Dim i As Long
Dim a As Long
Dim res As String
Dim code As String
res = ""
For i = 1 To Len(sStr)
a = AscW(Mid(sStr, i, 1))
If a < 128 Then
code = Mid(sStr, i, 1)
ElseIf ((a > 127) And (a < 2048)) Then
code = URLEncodeByte(((a \ 64) Or 192))
code = code & URLEncodeByte(((a And 63) Or 128))
Else
code = URLEncodeByte(((a \ 144) Or 234))
code = code & URLEncodeByte((((a \ 64) And 63) Or 128))
code = code & URLEncodeByte(((a And 63) Or 128))
End If
res = res & code
Next i
UTF8_URL_Encode = res
End Function
Private Function URLEncodeByte(val As Integer) As String
Dim res As String
res = "%" & Right("0" & Hex(val), 2)
URLEncodeByte = res
End Function

Functions work separately but not together, returns 0 value

I recently got help here with the first function but I am stumped about why my code is not working..
I'm trying to use the ReportTimeByOP function to find the newest file located in "sFolder" that begins with "sName" and that has a "sOPID" that matches the "value38" result of the ReadTextFile function.
For whatever reason I have no trouble getting both functions to work independently but my attempts to combine them into one seamless operation have failed. What I currently have is:
Function ReadTextFile(fpath)
Dim fline As String
Dim fnumb As Long
Dim i As Long
Dim Wanted As String
fnumb = FreeFile
Open fpath For Input As #fnumb
i = 1
Do While Not EOF(fnumb)
Line Input #fnumb, fline
If i = 2 Then
Wanted = Split(fline, vbTab)(38)
Exit Do
End If
i = i + 1
Loop
Close #fnumb
MsgBox fpath
ReadTextFile = Wanted
End Function
Function ReportTimeByOP(ByVal sName As String, ByVal sFolder As String, ByVal sOPID As String)
Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim value38 As String
Dim oFSO As FileSystemObject
If Right(sFolder, 1) <> "\" Then sFolder = sFolder & "\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FolderExists(sFolder) Then
FileName = Dir(sFolder & sName & "*hdr.txt", 0)
If FileName <> "" Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(sFolder & FileName)
Do While FileName <> ""
value38 = ReadTextFile(sFolder & FileName)
If FileDateTime(sFolder & FileName) > MostRecentDate And Trim(value38) = Trim(sOPID) Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(sFolder & FileName)
value38 = ReadTextFile(sFolder & FileName)
End If
FileName = Dir
DoEvents
Loop
End If
Else
MostRecentFile = "Err: folder not found."
End If
Set oFSO = Nothing
ReportTimeByOP = MostRecentDate
End Function
Given the huge number of files, I'd skip the Dir function entirely. I'd also skip the manual sorting of the results by creation date (I'm assuming this is the criteria - if not, it should be fairly easy to modify). Let the Windows Shell do the heavy lift for you. Unlike the VBA Dir() function or the Scripting.FileSystemObject, the shell dir command has a ton of parameters that allow you to retrieve sorted output. For this purpose, going through a list of files sorted in reverse order is much, much more efficient. You can see all of the dir options here.
So, I'd approach this by shelling to a dir command that retrieves the list of files in reverse date order, pipe it to a temp file, and then pick up the temp file to go through the list. That way you can just exit when you find your first match. Then you can simplify both your loop and ReadTextFile function by using the FileSystemObject:
ReadTextFile:
Public Function ReadTextFile(target As File) As String
With target.OpenAsTextStream
If Not .AtEndOfStream Then .SkipLine
Dim values() As String
If Not .AtEndOfStream Then
values = Split(.ReadLine, vbTab)
If UBound(values) >= 38 Then
ReadTextFile = values(38)
End If
End If
.Close
End With
End Function
ReportTimeByOP:
Function ReportTimeByOP(ByVal sName As String, ByVal sFolder As String, _
ByVal sOPID As String) As Date
With New Scripting.FileSystemObject
Dim temp As String
temp = .BuildPath(.GetSpecialFolder(TemporaryFolder), .GetTempName)
Dim seeking As String
seeking = .BuildPath(sFolder, sName & "*hdr.txt")
Shell "cmd /c dir """ & seeking & """ /b /a:-d /o:-d > " & temp
'Shell is asychronous - wait .2 seconds for it to complete.
Sleep 200
With .GetFile(temp).OpenAsTextStream
Dim directory() As String
directory = Split(.ReadAll, vbNewLine)
.Close
End With
.DeleteFile temp
Dim i As Long
Dim value38 As String
Dim candidate As File
'Temp file will end with a newline, so the last element is empty.
For i = LBound(directory) To UBound(directory) - 1
Set candidate = .GetFile(.BuildPath(sFolder, directory(i)))
value38 = ReadTextFile(candidate)
If Trim$(value38) = Trim$(sOPID) Then
ReportTimeByOP = candidate.DateCreated
Exit Function
End If
Next i
End With
End Function
And this declaration somewhere:
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

VBA - Opening a website and saving it as a .GIF extension

I am trying to open and then save a web page which contains an image as a .GIF extension to my desktop. The below code opens a test page for me:
Sub test()
Dim IE As Object, Doc As Object
Set IE = CreateObject("internetexplorer.application")
IE.Visible = True
IE.Navigate "http://www.orseu-concours.com/54-189-thickbox/epso-numerical-reasoning-test-2-en.jpg"
Do While IE.ReadyState <> 4: DoEvents: Loop
Set Doc = CreateObject("htmlfile")
Set Doc = IE.Document
End Sub
The next step is saving the page as a .GIF. The manual process for doing this is either right clicking the image and pressing save and then adding the .gif extension to the name or another way is to just press CTRL+S on the page and save it as an image that way.
I have tried API function URLDownloadToFile however the image I am using for my application updates every time the page is refreshed and I require the saved image to be the same as the one open therefore, cannot use the above function as it results in the two different images.
If possible, I am trying to avoid using SendKeys for this.
As per my comment, try the following (original code here):
Sub main()
'downloads google logo
HTTPDownload "https://www.google.tn/images/srpr/logo11w.png", "d:\logo11w.png"
End Sub
Sub HTTPDownload(myURL, myPath)
' This Sub downloads the FILE specified in myURL to the path specified in myPath.
'
' myURL must always end with a file name
' myPath may be a directory or a file name; in either case the directory must exist
'
' Written by Rob van der Woude
' http://www.robvanderwoude.com
'
' Based on a script found on the Thai Visa forum
' http://www.thaivisa.com/forum/index.php?showtopic=21832
' Standard housekeeping
Dim i, objFile, objFSO, objHTTP, strFile, strMsg
Const ForReading = 1, ForWriting = 2, ForAppending = 8
' Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the specified target file or folder exists,
' and build the fully qualified path of the target file
If objFSO.FolderExists(myPath) Then
strFile = objFSO.BuildPath(myPath, Mid(myURL, InStrRev(myURL, "/") + 1))
ElseIf objFSO.FolderExists(Left(myPath, InStrRev(myPath, "\") - 1)) Then
strFile = myPath
Else
WScript.Echo "ERROR: Target folder not found."
Exit Sub
End If
' Create or open the target file
Set objFile = objFSO.OpenTextFile(strFile, ForWriting, True)
' Create an HTTP object
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
' Write the downloaded byte stream to the target file
For i = 1 To LenB(objHTTP.ResponseBody)
objFile.Write Chr(AscB(MidB(objHTTP.ResponseBody, i, 1)))
Next
' Close the target file
objFile.Close
End Sub
Edit:
IE stores the image in the temp folder so you can pick it up from there and change the extension using the function above.
this is the same resonse on the poste here: Open webpage and save image
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
Private Sub Command1_Click()
Dim sin As String
Dim sout As String
Dim ret As Long
sin = "https://www.google.tn/images/srpr/logo11w.png"
sout = Environ("HOMEPATH") & "\Desktop\" & "logo11w.png"
ret = URLDownloadToFile(0, sin, sout, 0, 0)
If (ret = 0) Then MsgBox "Succedded" Else MsgBox "failed"
End Sub

Resources