Excel VBA: auto click and open file from website - vba

Thanks to Qharr, I have successfully performed auto search on the website.(My previous question:
Excel VBA: Cannot perform auto search on website)
I have another question concerning the next step: I would always like to click the first link that appears after clicking the search button, and open the file in order to extract certain data. Is there any ways to do that? Thanks!
Codes that I have at present:
Option Explicit
Sub Searchstockcode()
Dim SearchString As String, SearchBox As Object, SearchButton As Object, ie As Object
SearchString = "2828"
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate "http://www.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx"
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Set SearchBox = ie.document.getElementById("ctl00_txt_stock_code")
SearchBox.Value = SearchString
Set SearchButton = ie.document.querySelector("[src*='/image/search.gif']")
SearchButton.Click
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
'Click the first result
Set TargetFile = ie.document.getElementById("ctl00_gvMain_ctl02_hlTitle")
TargetFile.Click
'Here I would like to open the file in excel, but I am stuck at the "save as" pop up.
'As long as the file can be opened, I should be able to complete the data extraction with my own codes.
ie.Quit
End Sub

You can extract the URL for the file download and binary file download. In the example below, the file is stored in a variable wb for later use.
In the following the filedownload link is extracted via TargetFile.href and passed to a function to perform ADODB binary download. You could also pass the URL for download to URLMon as shown in my answer here.
Option Explicit
Public Sub Searchstockcode()
Dim SearchString As String, SearchBox As Object, SearchButton As Object, ie As Object
SearchString = "2828"
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate "http://www.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx"
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Set SearchBox = ie.document.getElementById("ctl00_txt_stock_code")
SearchBox.Value = SearchString
Set SearchButton = ie.document.querySelector("[src*='/image/search.gif']")
SearchButton.Click
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Dim TargetFile As Object
Set TargetFile = ie.document.getElementById("ctl00_gvMain_ctl02_hlTitle")
On Error Resume Next
Dim wb As Workbook
Set wb = Workbooks.Open(DownloadFile("C:\Users\User\Desktop\", TargetFile.href)) '< Replace with your download path here ending in "\"
On Error GoTo 0
'Other stuff
ie.Quit
End Sub
Public Function DownloadFile(ByVal downloadFolder As String, ByVal downloadURL As String) As String
Dim http As Object , tempArr As Variant
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.Open "GET", downloadURL, False
http.send
On Error GoTo errhand
With CreateObject("ADODB.Stream")
.Open
.Type = 1
.write http.responseBody
tempArr = Split(downloadURL, "/")
tempArr = tempArr(UBound(tempArr))
.SaveToFile downloadFolder & tempArr, 2 '< "/" on enter of downloadFolder. 2 for overwrite which is Ok if no file modifications.
.Close
End With
DownloadFile = downloadFolder & tempArr
Exit Function
errhand:
If Err.Number <> 0 Then
Debug.Print Err.Number, Err.Description
MsgBox "Download failed"
End If
DownloadFile = vbNullString
End Function
URLMon version:
Option Explicit
Public Const BINDF_GETNEWESTVERSION As Long = &H10
#If VBA7 And Win64 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 LongPtr, _
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
Public Sub Searchstockcode()
Dim SearchString As String, SearchBox As Object, SearchButton As Object, ie As Object
SearchString = "2828"
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate "http://www.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx"
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Set SearchBox = ie.document.getElementById("ctl00_txt_stock_code")
SearchBox.Value = SearchString
Set SearchButton = ie.document.querySelector("[src*='/image/search.gif']")
SearchButton.Click
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Dim TargetFile As Object
Set TargetFile = ie.document.getElementById("ctl00_gvMain_ctl02_hlTitle")
On Error Resume Next
Dim wb As Workbook
Set wb = Workbooks.Open(downloadFile("C:\Users\User\Desktop\", TargetFile.href)) '< Replace with your download path here ending in "\"
On Error GoTo 0
'Other stuff
ie.Quit
End Sub
Public Function downloadFile(ByVal downloadFolder As String, ByVal URL As String) As String
Dim tempArr As Variant, ret As Long
tempArr = Split(URL, "/")
tempArr = tempArr(UBound(tempArr))
ret = URLDownloadToFile(0, URL, downloadFolder & tempArr, BINDF_GETNEWESTVERSION, 0)
downloadFile = downloadFolder & tempArr
End Function

Related

VBA: Excel macro code correction

I am looking for a VBA code that can help me to click a button from a web page. I got the below VBA from one of the sites which works as expected.
Sub followWebsiteLink()
Dim ie As InternetExplorer
Dim html As HTMLDocument
Dim Link As Object
Dim ElementCol As Object
Application.ScreenUpdating = False
Set ie = New InternetExplorer
ie.Visible = True
ie.navigate "https://www.google.co.in"
Do While ie.readyState <> READYSTATE_COMPLETE
Application.StatusBar = "Loading website…"
DoEvents
Loop
Set html = ie.document
Set ElementCol = html.getElementsByTagName("a")
For Each Link In ElementCol
If Link.innerHTML = "Google Pixel 2" _ 'Or u can use "Advertising"
Then
Link.Click
End If
Next Link
Set ie = Nothing
Application.StatusBar = ""
Application.ScreenUpdating = True
End Sub
But if I replace it with the site name I want, it wont work.
**The changes I made are as follows **
ie.navigate "https://www.flipkart.com/"
For Each Link In ElementCol
If Link.innerHTML = "Log In" _
And Link.getElementsByClassName = "_2k0gmP" _
Then
Link.Click
End If
Next Link
Try this code, worked for me to click on Log In
Code
#If VBA7 Then
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
Sub test()
Dim IE As Object
Dim htmlDoc As Object
Dim sURL As String
' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")
sURL = "https://www.flipkart.com/"
' WEBPAGE NAVIGATION
With IE
.navigate (sURL)
.Visible = True
End With
WaitIE IE, 2000
' CLICK ON LOG IN
Set htmlDoc = IE.document
Set buttonclick = htmlDoc.getElementsByClassName("_2k0gmP")
buttonclick(7).Click
WaitIE IE, 5000
'IE.Quit
'Set IE = Nothing
End Sub
Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
Sleep time
Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.readyState = 4) & _
vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
i = i + 1
Loop Until IE.readyState = 4 Or Not IE.Busy
End Sub
Edit
You can use this code to get the href:
For Each Element In buttonclick
Debug.Print Element.href
Next
Or to get the InnerText:
For Each Element In buttonclick
Debug.Print Element.innerText & " " & i
i = i + 1
Next
'Where i is the number of the item
Then you can use conditional such as:
For Each Element In buttonclick
If Element.href = "href_link" Then Element.Click
Next
OR
For Each Element In buttonclick
If Element.innerText = "Log In" Then Element.Click
Next

VBA IE approve download in dialog window

Attempting to download data using a link to a file. IE opens and navigates to the file but a popup window asks me to open the file. I need to click this open button. Requesting help with navigating the pop up. Here is my code thus far:
Sub GetData()
Const cURL = "http://www.bankofengland.co.uk/statistics/Documents/yieldcurve/ukinf05.xlsx"
Dim IE As InternetExplorer
Dim doc As HTMLDocument
Dim HTMLelement As IHTMLElement
Set IE = New InternetExplorer
IE.Visible = False
IE.Navigate cURL
End Sub
As #Comintern had suggested, and with a little checking on this blog entry by SiddarthRout
Option Explicit
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
Dim Ret As Long
Sub Sample()
Dim strURL As String
Dim strPath As String
'~~> URL of the Path
strURL = "http://www.bankofengland.co.uk/statistics/Documents/yieldcurve/ukinf05.xlsx"
'~~> Destination for the file
strPath = "C:\temp\ukinf05.xlsx"
Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)
If Ret = 0 Then
MsgBox "File successfully downloaded"
Else
MsgBox "Unable to download the file"
End If
End Sub
The end result I got was the file, correctly in my C:\temp\ folder.

Interact with Active/Single IE11 Session VBA

So I have a loop that exports data from a website. However, for each case, it starts a new session and closes. Is there a method to navigate and download for all the cases in just one IE11 session and then closing out? Below is the code that I have right now:
Public Sub Get_File()
Dim sFiletype As String 'Fund type reference
Dim sFilename As String 'File name (fund type + date of download), if "" then default
Dim sFolder As String 'Folder name (fund type), if "" then default
Dim bReplace As Boolean 'To replace the existing file or not
Dim sURL As String 'The URL to the location to extract information
Dim Cell, Rng As Range
Dim Sheet As Worksheet
'Initialize variables
Set Rng = Range("I2:I15")
Set Sheet = ActiveWorkbook.Sheets("Macro_Button")
For Each Cell In Rng
If Cell <> "" Then
sFiletype = Cell.Value
sFilename = sFiletype & "_" & Format(Date, "mmddyyyy")
sFolder = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:J15"), 2, False)
bReplace = True
sURL = "www.preqin.com"
'Download using the desired approach, XMLHTTP / IE
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:W15"), 15, False) = 1 Then
Call Download_Use_IE(sURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(sURL, sFilename, sFolder, bReplace)
End If
Else
Exit Sub
End If
Next
End Sub
Private Sub Download_Use_IE(ByRef sURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim oBrowser As InternetExplorer
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
'Create IE object
Set oBrowser = New InternetExplorer
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Skips log in step if already signed into website
On Error GoTo LoggedIn
'Enter username
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_email").Value = "XXX"
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_password").Value = "XXX"
'Submit the sign in
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_btnLogin").Click
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
LoggedIn:
'All PE
oBrowser.navigate Range("H3").Value
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Set the htmldocument
Set hDoc = oBrowser.document
'Loop and click the download file button
Set objInputs = oBrowser.document.getElementsbyTagName("input")
For Each ele In objInputs
If ele.Title Like "Download Data to Excel" Then
ele.Click
End If
Next
'Wait for dialogue box to load
While oBrowser.Busy Or oBrowser.readyState > 3: DoEvents: Wend
Application.Wait (Now + TimeValue("0:00:02"))
'IE 9+ requires to confirm save
Call Download(oBrowser, sFilename, sFolder, bReplace)
'Close IE
oBrowser.Quit
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Modify your download_IE procedure to use a Browser that is passed to it:
Private Sub Download_Use_IE(oBrowser As InternetExplorer, _
ByRef sURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
'Create IE object
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
......rest of code
Call Download(oBrowser, sFilename, sFolder, bReplace)
'Do not Close IE
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Then modify your procedure to pass this object:
Public Sub Get_File()
'declare all variables plus:
Dim oBrowser As InternetExplorer
Set oBrowser = New InternetExplorer
.....put additional code here.....
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:W15"), 15, False) = 1 Then
Call Download_Use_IE(oBrowser, sURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(oBrowser, sURL, sFilename, sFolder, bReplace)
End If
Else
Exit Sub
End If
Next
'Close IE
oBrowser.Quit
End Sub
You will need to do the same thing for the other procedure.

Saving webpage as PDF to certain directory

I have it where it will open Internet Explorer give the user the save as box and then exit. However, I would prefer if instead of the user having to navigate to the correct folder, the directory comes from a cell in the worksheet and saves the webpage as a PDF. I have full Adobe installed. The code:
Sub WebSMacro()
Dim IE As Object
Dim Webloc As String
Dim FullWeb As String
Webloc = ActiveSheet.Range("B39").Value
FullWeb = "http://www.example.com=" & Webloc
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate FullWeb
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
IE.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER
Application.Wait DateAdd("s", 10, Now)
IE.Quit
Set IE = Nothing
End Sub
Today, you win the Internet!
Since I wanted to learn this more in depth for my own personal benefit, I used the code in the 2nd link I referenced in my comment to get the code to work as you have defined it.
The code will enter the FilePath and Name (gathered from a Cell) into the SaveAs Dialog Box and save it to the entered location.
Here is the main sub (with comments):
Sub WebSMacro()
'set default printer to AdobePDF
Dim WSHNetwork As Object
Set WSHNetwork = CreateObject("WScript.Network")
WSHNetwork.SetDefaultPrinter "Adobe PDF"
'get pdfSave as Path from cell range
Dim sFolder As String
sFolder = Sheets("Sheet1").Range("A1") 'assumes folder save as path is in cell A1 of mySheets
Dim IE As Object
Dim Webloc As String
Dim FullWeb As String
Webloc = ActiveSheet.Range("B39").Value
FullWeb = "http://www.example.com" & Webloc
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.Navigate FullWeb
Do While .Busy
Application.Wait DateAdd("s", 1, Now)
Loop
.ExecWB 6, 2 'OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER
Application.Wait DateAdd("s", 3, Now)
Call PDFPrint(sFolder & Webloc & ".pdf")
.Quit
End With
Set IE = Nothing
End Sub
You will also need to place this two subs somewhere in your workbook (can be the same module as the main sub (or different one)):
Sub PDFPrint(strPDFPath As String)
'Prints a web page as PDF file using Adobe Professional.
'API functions are used to specify the necessary windows while
'a WMI function is used to check printer's status.
'By Christos Samaras
'http://www.myengineeringworld.net
Dim Ret As Long
Dim ChildRet As Long
Dim ChildRet2 As Long
Dim ChildRet3 As Long
Dim comboRet As Long
Dim editRet As Long
Dim ChildSaveButton As Long
Dim PDFRet As Long
Dim PDFName As String
Dim StartTime As Date
'Find the main print window.
StartTime = Now()
Do Until Now() > StartTime + TimeValue("00:00:05")
Ret = 0
DoEvents
Ret = FindWindow(vbNullString, "Save PDF File As")
If Ret <> 0 Then Exit Do
Loop
If Ret <> 0 Then
SetForegroundWindow (Ret)
'Find the first child window.
StartTime = Now()
Do Until Now() > StartTime + TimeValue("00:00:05")
ChildRet = 0
DoEvents
ChildRet = FindWindowEx(Ret, ByVal 0&, "DUIViewWndClassName", vbNullString)
If ChildRet <> 0 Then Exit Do
Loop
If ChildRet <> 0 Then
'Find the second child window.
StartTime = Now()
Do Until Now() > StartTime + TimeValue("00:00:05")
ChildRet2 = 0
DoEvents
ChildRet2 = FindWindowEx(ChildRet, ByVal 0&, "DirectUIHWND", vbNullString)
If ChildRet2 <> 0 Then Exit Do
Loop
If ChildRet2 <> 0 Then
'Find the third child window.
StartTime = Now()
Do Until Now() > StartTime + TimeValue("00:00:05")
ChildRet3 = 0
DoEvents
ChildRet3 = FindWindowEx(ChildRet2, ByVal 0&, "FloatNotifySink", vbNullString)
If ChildRet3 <> 0 Then Exit Do
Loop
If ChildRet3 <> 0 Then
'Find the combobox that will be edited.
StartTime = Now()
Do Until Now() > StartTime + TimeValue("00:00:05")
comboRet = 0
DoEvents
comboRet = FindWindowEx(ChildRet3, ByVal 0&, "ComboBox", vbNullString)
If comboRet <> 0 Then Exit Do
Loop
If comboRet <> 0 Then
'Finally, find the "edit property" of the combobox.
StartTime = Now()
Do Until Now() > StartTime + TimeValue("00:00:05")
editRet = 0
DoEvents
editRet = FindWindowEx(comboRet, ByVal 0&, "Edit", vbNullString)
If editRet <> 0 Then Exit Do
Loop
'Add the PDF path to the file name combobox of the print window.
If editRet <> 0 Then
SendMessage editRet, WM_SETTEXT, 0&, ByVal " " & strPDFPath
keybd_event VK_DELETE, 0, 0, 0 'press delete
keybd_event VK_DELETE, 0, KEYEVENTF_KEYUP, 0 ' release delete
'Get the PDF file name from the full path.
On Error Resume Next
PDFName = Mid(strPDFPath, WorksheetFunction.Find("*", WorksheetFunction.Substitute(strPDFPath, "\", "*", Len(strPDFPath) _
- Len(WorksheetFunction.Substitute(strPDFPath, "\", "")))) + 1, Len(strPDFPath))
On Error GoTo 0
'Save/print the web page by pressing the save button of the print window.
Sleep 1000
ChildSaveButton = FindWindowEx(Ret, ByVal 0&, "Button", "&Save")
SendMessage ChildSaveButton, BM_CLICK, 0, 0
'Sometimes the printing delays, especially in large colorful web pages.
'Here the code checks printer status and if is idle it means that the
'printing has finished.
Do Until CheckPrinterStatus("Adobe PDF") = "Idle"
DoEvents
If CheckPrinterStatus("Adobe PDF") = "Error" Then Exit Do
Loop
'Since the Adobe Professional opens after finishing the printing, find
'the open PDF document and close it (using a post message).
StartTime = Now()
Do Until StartTime > StartTime + TimeValue("00:00:05")
PDFRet = 0
DoEvents
PDFRet = FindWindow(vbNullString, PDFName & " - Adobe Acrobat")
If PDFRet <> 0 Then Exit Do
Loop
If PDFRet <> 0 Then
PostMessage PDFRet, WM_CLOSE, 0&, 0&
End If
End If
End If
End If
End If
End If
End If
End Sub
Function CheckPrinterStatus(strPrinterName As String) As String
'Provided the printer name the functions returns a string
'with the printer status.
'By Christos Samaras
'http://www.myengineeringworld.net
Dim strComputer As String
Dim objWMIService As Object
Dim colInstalledPrinters As Variant
Dim objPrinter As Object
'Set the WMI object and the check the install printers.
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery("Select * from Win32_Printer")
'If an error occurs in the previous step, the function will return error.
If Err.Number <> 0 Then
CheckPrinterStatus = "Error"
End If
On Error GoTo 0
'The function loops through all installed printers and for the selected printer,
'checks it status.
For Each objPrinter In colInstalledPrinters
If objPrinter.Name = strPrinterName Then
Select Case objPrinter.PrinterStatus
Case 1: CheckPrinterStatus = "Other"
Case 2: CheckPrinterStatus = "Unknown"
Case 3: CheckPrinterStatus = "Idle"
Case 4: CheckPrinterStatus = "Printing"
Case 5: CheckPrinterStatus = "Warmup"
Case 6: CheckPrinterStatus = "Stopped printing"
Case 7: CheckPrinterStatus = "Offline"
Case Else: CheckPrinterStatus = "Error"
End Select
End If
Next objPrinter
'If there is a blank status the function returns error.
If CheckPrinterStatus = "" Then CheckPrinterStatus = "Error"
End Function
And finally Declare these constants and functions in a module as well (can be the same module as the main sub (or different one).
Option Explicit
Public Declare Sub Sleep Lib "kernel32" _
(ByVal dwMilliseconds As Long)
Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Public Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Public Declare Function SetForegroundWindow Lib "user32" _
(ByVal hWnd As Long) As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Function SendMessageByString Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Public Declare Function PostMessage Lib "user32" Alias "PostMessageA" _
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Sub keybd_event Lib "user32" _
(ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
'Constants used in API functions.
Public Const SW_MAXIMIZE = 3
Public Const WM_SETTEXT = &HC
Public Const VK_DELETE = &H2E
Public Const KEYEVENTF_KEYUP = &H2
Public Const BM_CLICK = &HF5&
Public Const WM_CLOSE As Long = &H10

Hide all the tasks happening during the Macro Process

I want to hide the following tasks that happens in front of the Excel workbook:
Hide the file copying process window (from the unzip process) happening in front of the Excel workbook
(###Note: The window for copying process comes up sometimes and sometimes not).. Please find the sample screenshot for it below:
Hide the cmd prompt process window (from the .bat file) happening in front of the Excel workbook
How can we hide the above two tasks and somehow put it behind the workbook.
Part of my full code is given below:
Option Explicit
#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 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 Open_Dialog()
'Disable Screen Updating and Events
Application.EnableEvents = False
Application.ScreenUpdating = False
Dim fd As Office.FileDialog
Dim sFolderName As String
Dim DownloadFile$
Dim URL$
Dim LocalFilename$
Dim done
Dim ZipFolderAndFileName As Variant
Dim FileNameFolder As Variant
Dim FSO As Object
Dim oApp As Object
Dim aFile As String
Dim txtFileName As String
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Use File Picker To Pick a File Name
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select a file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Executable File", "*.exe"
.Filters.Add "Word 97-2003 Doc File", "*.doc"
.Filters.Add "Word Doc File", "*.docx"
.Filters.Add "Text File", "*.txt"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show <> -1 Then
Exit Sub
End If
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End With
'Get the Folder Name from the file name (the file name itself is not used)
'Append a trailing backslash to the Folder Name if needed
sFolderName = LjmExtractPath(txtFileName)
If Right(sFolderName, 1) <> "\" Then
sFolderName = sFolderName & "\"
End If
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Download the .zip file to the destination folder
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
DownloadFile$ = "pads_strings.zip"
URL$ = "http://sagamusix.de/sample_collection/" & DownloadFile
LocalFilename$ = sFolderName & DownloadFile
done = URLDownloadToFile(0, URL, LocalFilename, 0, 0)
If done = 0 Then
'Do nothing
Else
MsgBox "Couldn't connect to the internet. Please check you internet connection!"
Exit Sub
End If
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Extract the files from the zip file to the Destination Folder
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Create the 'Variant' names required by oApp.Namespace
FileNameFolder = sFolderName
ZipFolderAndFileName = LocalFilename$
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(ZipFolderAndFileName).items
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Delete the temporary files
'Delete the downloaded .zip file
'Clear object pointers
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
aFile = LocalFilename
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
Set fd = Nothing
Set oApp = Nothing
Dim Batch_File As String
Batch_File = FreeFile()
Open ThisWorkbook.path & "BatchFile.bat" For Output As #Batch_File
Print #Batch_File, "cd "
Print #Batch_File, "waitfor /t 5 simon"
Close #Batch_File
Batch_File = Shell(ThisWorkbook.path & "BatchFile.bat", vbMaximizedFocus)
'Disable Screen Updating and Events
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Public Function LjmExtractPath(sPathAndName As String)
'This extracts the path with a trailing '\'
LjmExtractPath = Left(sPathAndName, InStrRev(sPathAndName, "\"))
End Function
Actually cmd prompt process has lot of other tasks in the .bat file. I have only provided some of it.
I have tried using the code below but in vain..it doesn't hide only those two tasks mentioned above:
Application.EnableEvents = False
Application.ScreenUpdating = False
'my code
Application.ScreenUpdating = True
Application.EnableEvents = True
Attached is my .bat file. Please find the link below for it.
click here to download my .bat file