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

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

Related

Excel VBA Selenium - Image Click

https://www.laquintaca.gov/connect/short-term-vacation-rentals
The site above has a cluster of images. On of those images is a box with the text value "ACTIVE AND SUSPENDED PERMITS". Click on the image takes you to a PDF that is downloadable. I would like to automate that download process to my desktop. The "orange" image stays the same but the href address changes every two weeks(document serial number on the end) when they upload a new PDF.
More directly, How do i click on the orage image space to get to the underlying, but bi-weekly changing PDF?
I can not find the actionable object address to click to take me to the downloadable document. What is the VBA Selenium code line to "click"
'*****************************************************************************
Sub FindingElements()
Set cd = New Selenium.ChromeDriver
cd.Start
cd.Get "https://www.laquintaca.gov/connect/short-term-vacation-rentals"
'"https://www.laquintaca.gov/connect/short-term-vacation-rentals"
'=================================================================
'Find Element By ID or Name
'=================================================================
Dim SearchInput As Selenium.WebElement
Dim SearchButton As Selenium.WebElement
Dim FindBy As New Selenium.By
'
If Not cd.IsElementPresent(FindBy.ID("OuterContainer")) Then
MsgBox "Could not find search input box"
Exit Sub
End If
'
' Set SearchInput = cd.FindElementById("OuterContainer")
' Set SearchInput = cd.FindElement(FindBy.ID("searchInput"))
' Set SearchInput = cd.FindElementByName("search")
' Set SearchInput = cd.FindElementByCss("#searchInput")
' Set SearchInput = cd.FindElementByCss("[name='search']")
' Set SearchInput = cd.FindElementByXPath("//*[#id='searchInput']")
You can do it with CSS or XPath. I prefer CSS because XPath is more complex and sometimes slower than CSS.
The first procedure waits until the file is downloaded.
I used a procedure by Paul_Hossler to find the ChromeDownloadFolder.
Sub DownloadFileFromLaquintaca()
Dim cd As New Selenium.ChromeDriver
Dim DefaultChromeDownloadFolder As String
' Get Chrome download folder
DefaultChromeDownloadFolder = ChromeDownloadFolder
' Start Chrome
cd.Start
' Navigate to
cd.Get "https://www.laquintaca.gov/connect/short-term-vacation-rentals"
Dim FindBy As New Selenium.By
Dim imgElement As Selenium.WebElement
' Check if element is present with CSS
If Not cd.IsElementPresent(FindBy.Css("img[alt='ACTIVE & SUSPENDED PERMITS BOX']")) Then
MsgBox "Could not find image box"
Exit Sub
End If
' Click to download
cd.FindElementByCss("img[alt='ACTIVE & SUSPENDED PERMITS BOX']").Click
' Wait until download is completed
Do While Dir(DefaultChromeDownloadFolder & "\" & "STVRCurrentActiveSuspended.pdf") = ""
DoEvents
Loop
End Sub
Function ChromeDownloadFolder()
' By Paul_Hossler
Dim sPref As String
Dim iFile As Long, iStart As Long, iEnd As Long
Dim sBuffer As String, sSearch As String, sDownloads As String
' Chrome preferces file, no extension
sPref = Environ("LOCALAPPDATA") & "\Google\Chrome\User Data\Default\Preferences"
' marker
sSearch = """download"":{""default_directory"":"
' read the whole file into buffer
iFile = FreeFile
Open sPref For Input As #iFile
sBuffer = Input$(LOF(iFile), iFile)
Close #iFile
' find start of marker
iStart = InStr(1, sBuffer, sSearch, vbTextCompare)
' find comma
iEnd = InStr(iStart + Len(sSearch), sBuffer, ",", vbTextCompare)
' pull out path
sDownloads = Mid(sBuffer, iStart + Len(sSearch) + 1, iEnd - iStart - Len(sSearch) - 2)
' remove double back slashes
ChromeDownloadFolder = Replace(sDownloads, "\\", "\")
End Function
I solved the issue I was having with the SUB below that works perfectly. Thank you so much for you fantastic help. The code blow swithces to the Current code tab, reds the URL then downloads to a location via the WinHttpReq = CreateObject("Microsoft.XMLHTTP") process:
Sub DownloadFileFromLaquintaca2()
Dim cd As New selenium.ChromeDriver
Dim DefaultChromeDownloadFolder As String
Dim MyURL As String
' Start Chrome
Set cd = New ChromeDriver
cd.Start
' Navigate to
cd.get "https://www.laquintaca.gov/connect/short-term-vacation-rentals"
Const URL = "https://www.laquintaca.gov/connect/short-term-vacation-rentals"
Dim FindBy As New selenium.By
Dim imgElement As selenium.WebElement
' Check if element is present with CSS
If Not cd.IsElementPresent(FindBy.Css("img[alt='ACTIVE & SUSPENDED PERMITS BOX']")) Then
MsgBox "Could not find image box"
Exit Sub
End If
cd.FindElementByCss("img[alt='ACTIVE & SUSPENDED PERMITS BOX']").Click
Application.Wait (Now + TimeValue("0:00:3"))
'Get URL Address in Second Chorme Tab
With cd
'.get URL
.SwitchToNextWindow
MyURL = .URL
'Debug.Print .Window.Title
'Debug.Print myURL
.Windows.Item(.Windows.Count - 1).Close 'close prior window
End With
'Write PDF File into Location with file Name STVR.PDF ---D:\MyDownLoads\STVR.pdf
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", MyURL, False, "username", "password"
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile "D:\MyDownLoads\STVR.pdf", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
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

Open a page in a pdf using VBA in 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

Accessing an image that's inside of an Excel Table via VBA

I am designing a VBA Form in Excel. The Workbook has a table called "images", and inside there I am dropping some images from my local hard drive.
These Workbook & UserForm are to be shared with my colleagues. They might not have these images in their harddrive, but they will have them inside of the Excel table.
I am looking for a way to load an image that's inside of a table inside of an "Image" VBA form control.
In Google all I find is how to load an image from my hard drive (i.e. using an absolute path like "C:/my_images/car.png"). What I can't find is how to load an image that's within a table, i.e. already bundled within the Workbook.
Any ideas?
If you are still interested in this question, I came up with a solution.
First you need to export the picture from the shape into a file. I found that only .jpg files can be used. My code generates a temporary filename (you need to be able to read/write that path but I think it is usually not a problem), and saves the picture by inserting it into a ChartObject, which can export its contents as a picture. I suppose this process may modify (e.g. compress) the original data but I saw no visible difference on the screen.
When this is done, it loads the picture from this file into the Image control on the UserForm.
Finally, it deletes the temporary file to clean up this side-effect.
Option Explicit
' Include: Tools > References > Microsoft Scripting Runtime
Private Sub cmdLoad_Click()
' Assumption: The UserForm on which you want to load the picture has a CommandButton, cmdLoad, and this function is its event handler
Dim imgImageOnForm As Image: Set imgImageOnForm = imgTarget ' TODO: Set which Control you want the Picture loaded into. You can find the Name in the VBA Form Editor's Properties Bar
Dim strSheetName As String: strSheetName = "TargetSheet" ' TODO: Specify the Name of the Worksheet where your Shape (picture) is
Dim strShapeName As String: strShapeName = "TargetPicture" ' TODO: Specify the Name of your Shape (picture) on the Worksheet
Dim strTemporaryFile As String: strTemporaryFile = GetTemporaryJpgFileName ' TODO: Give a path for the temporary file, the file extension is important, e.g. .jpg can be loaded into Form Controls, while .png cannot
LoadShapePictureToFormControl _
strSheetName, _
strShapeName, _
imgImageOnForm, _
strTemporaryFile
End Sub
Private Sub LoadShapePictureToFormControl(strSheetName As String, strShapeName As String, imgDst As MSForms.Image, strTemporaryFile As String)
' Note: This Sub overwrites the contents of the Clipboard
' Note: This Sub creates and deletes a temporary File, therefore it needs access rights to do so
Dim shpSrc As Shape: Set shpSrc = ThisWorkbook.Worksheets(strSheetName).Shapes(strShapeName)
Dim strTmp As String: strTmp = strTemporaryFile
ExportShapeToPictureFile shpSrc, strTmp
ImportPictureFileToImage strTmp, imgDst
FileSystem.Kill strTmp
End Sub
Private Sub ExportShapeToPictureFile(shpSrc As Shape, strDst As String)
shpSrc.CopyPicture xlScreen, xlBitmap
Dim chtTemp As ChartObject: Set chtTemp = shpSrc.Parent.ChartObjects.Add(0, 0, shpSrc.Width, shpSrc.Height)
With chtTemp
.Activate
.Parent.Shapes(.Name).Fill.Visible = msoFalse
.Parent.Shapes(.Name).Line.Visible = msoFalse
.Chart.Paste
.Chart.Export strDst
.Delete
End With
End Sub
Private Sub ImportPictureFileToImage(strSrc As String, imgDst As MSForms.Image)
Dim ipdLoaded As IPictureDisp: Set ipdLoaded = StdFunctions.LoadPicture(strSrc)
Set imgDst.Picture = ipdLoaded
End Sub
Private Function GetTemporaryJpgFileName() As String
Dim strTemporary As String: strTemporary = GetTemporaryFileName
Dim lngDot As Long: lngDot = InStrRev(strTemporary, ".")
If 0 < lngDot Then
strTemporary = Left(strTemporary, lngDot - 1)
End If
strTemporary = strTemporary & ".jpg"
GetTemporaryJpgFileName = strTemporary
End Function
Private Function GetTemporaryFileName() As String
Dim fsoTemporary As FileSystemObject: Set fsoTemporary = New FileSystemObject
Dim strResult As String: strResult = fsoTemporary.GetSpecialFolder(TemporaryFolder)
strResult = strResult & "\" & fsoTemporary.GetTempName
GetTemporaryFileName = strResult
End Function

How to click on open on the open/save/cancel dialog box- IE and VBA

I am trying to download a report from my company's site for reporting purposes.
Steps for:
Open IE
Go to download link
Click on extract button
click on open button on the IE dialog box(save/open/cancel box)
Copy the data to sheet 1 of my active workbook
Close IE
I have done till step 3. I am having trouble with step 4. I tried the below solutions but they did not work for me.
How to check if Open/Save/Cancel bar appeared
Automate saveas dialogue for IE9 (vba)
Code Used:
Sub ExtractGLfile()
Set ie = New InternetExplorerMedium
Dim DLCPortalGL As String
DLCPortalGL = "link"
ie.Visible = True
ie.navigate (DLCPortalGL)
Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE
ie.document.getElementById("ButtonID").Click
I need help with step 4 - clicking on open of the open/save/cancel button.
UPDATES: I was able to download the file using the below code
Application.SendKeys "%{O}", True
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 10
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
SendKeys "{TAB}", True
SendKeys "{ENTER}", True
However while the file opens, I am getting error: enter image description here
Any suggestions?
If you are trying to simply download a page or file, you can use this fast function DownloadFile:
Option Compare Database
Option Explicit
' API declarations.
'
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
' Download a file or a page with public access from the web.
' Returns 0 if success, error code if not.
'
' If parameter NoOverwrite is True, no download will be attempted
' if an existing local file exists, thus this will not be overwritten.
'
' Examples:
'
' Download a file:
' Url = "https://www.codeproject.com/script/Membership/ProfileImages/%7Ba82bcf77-ba9f-4ec3-bbb3-1d9ce15cae23%7D.jpg"
' FileName = "C:\Test\CodeProjectProfile.jpg"
' Result = DownloadFile(Url, FileName)
'
' Download a page:
' Url = "https://www.codeproject.com/Tips/1022704/Rounding-Values-Up-Down-By-Or-To-Significant-Figur?display=Print"
' FileName = "C:\Test\CodeProject1022704.html"
' Result = DownloadFile(Url, FileName)
'
' Error codes:
' -2146697210 "file not found".
' -2146697211 "domain not found".
' -1 "local file could not be created."
'
' 2004-12-17. Gustav Brock, Cactus Data ApS, CPH.
' 2017-05-25. Gustav Brock, Cactus Data ApS, CPH. Added check for local file.
' 2017-06-05. Gustav Brock, Cactus Data ApS, CPH. Added option to no overwrite the local file.
'
Public Function DownloadFile( _
ByVal Url As String, _
ByVal LocalFileName As String, _
Optional ByVal NoOverwrite As Boolean) _
As Long
Const BindFDefault As Long = 0
Const ErrorNone As Long = 0
Const ErrorNotFound As Long = -1
Dim Result As Long
If NoOverwrite = True Then
' Page or file should not be overwritten.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) <> "" Then
' File exists. Don't proceed.
Exit Function
End If
End If
' Download file or page.
' Return success or error code.
Result = URLDownloadToFile(0, Url & vbNullChar, LocalFileName & vbNullChar, BindFDefault, 0)
If Result = ErrorNone Then
' Page or file was retrieved.
' Check that the local file exists.
If Dir(LocalFileName, vbNormal) = "" Then
Result = ErrorNotFound
End If
End If
DownloadFile = Result
End Function
The full story - and about caching or not - can be found here.

Resources