Hide all the tasks happening during the Macro Process - vba

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

Related

copy a folder- and all subfolders - without overwriting existing

0
I am trying to create a backup database on a network drive using fso.folder copy. My intention is to move all files and subfolder within the folder, but if a file already exists on the backup drive, skip it, and copy the remainder of the files in the folder.
FSO.copyfolder Source:=Sourcefilename, Destination:=Destinfilename, OverwriteFiles:= False
However, the script errors when it finds the existing file. Any advice would be appreciated.
Please, try the next code:
Sub testCopyFolder()
Dim FSO As Object, SourceFold As String, DestinationFold As String
SourceFold = "Source folder path" ' ending in "\"
DestinationFold = "Destination folder path" ' ending in "\"
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(DestinationFold) Then
FSO.CopyFolder SourceFold, DestinationFold
End If
End Sub
You can proceed in a similar way in order to copy files. Of course, using FSO.FileExists()...
Backup Folder and Its Subfolders Without Overwriting
The following will backup a Source Folder to a Destination Folder i.e. copy missing folders and files.
TESTcopyFolder is just an example how you could use the solution.
It will call the initializing procedure, backupFolder, which will call backupFolderCopy and backupFolderRecurse when necessary.
The declaration Private SkipPath As String and the three procedures have to be copied to the same (usually standard) module, e.g. Module1.
The Code
Option Explicit
Private SkipPath As String
Sub TESTcopyFolder()
Const srcPath As String = "F:\Test\2020\65412587\Test1"
Const dstPath As String = "F:\Test\2020\65412587\Test2"
backupFolder srcPath, dstPath
' Open Destination Path in File Explorer.
'ThisWorkbook.FollowHyperlink dstPath
End Sub
' Initialize
Sub backupFolder( _
ByVal srcPath As String, _
ByVal dstPath As String, _
Optional ByVal backupSubFolders As Boolean = True)
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
With fso
If .FolderExists(srcPath) Then
backupFolderCopy fso, srcPath, dstPath
If backupSubFolders Then
SkipPath = ""
backupFolderRecurse fso, srcPath, dstPath
End If
MsgBox "Backup updated.", vbInformation, "Success"
Else
MsgBox "Source Folder does not exist.", vbCritical, "No Source"
End If
End With
End Sub
' Copy Folders
Private Function backupFolderCopy( _
fso As Object, _
ByVal srcPath As String, _
ByVal dstPath As String) _
As String
With fso
If .FolderExists(dstPath) Then
Dim fsoFile As Object
Dim dstFilePath As String
For Each fsoFile In .GetFolder(srcPath).Files
dstFilePath = .BuildPath(dstPath, fsoFile.Name)
' Or:
'dstFilePath = Replace(fsoFile.Path, srcPath, dstPath)
If Not .FileExists(dstFilePath) Then
.CopyFile fsoFile.Path, dstFilePath
End If
Next fsoFile
'backupFolderCopy = "" ' redundant: it is "" by default.
Else
.CopyFolder srcPath, dstPath
backupFolderCopy = srcPath
End If
End With
End Function
' Copy SubFolders
Private Sub backupFolderRecurse( _
fso As Object, _
ByVal srcPath As String, _
ByVal dstPath As String)
Dim fsoFolder As Object: Set fsoFolder = fso.GetFolder(srcPath)
Dim fsoSubFolder As Object
Dim srcNew As String
Dim dstNew As String
For Each fsoSubFolder In fsoFolder.SubFolders
srcNew = fsoSubFolder.Path
dstNew = fso.BuildPath(dstPath, fsoSubFolder.Name)
' Or:
'dstNew = Replace(srcNew, srcPath, dstPath)
If Len(SkipPath) = 0 Or Left(srcNew, Len(SkipPath)) <> SkipPath Then
SkipPath = backupFolderCopy(fso, srcNew, dstNew)
backupFolderRecurse fso, srcNew, dstNew
End If
Next
End Sub

Excel VBA: auto click and open file from website

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

How to copy embeded object and paste in temp folder with VBA

I have to create a code to save configuration script of routers from specified list.
Using telnet and VBA I'm able to fulfill my requirement. But telnet window is visible every time and also I have to rely on SendKeys to send Commands properly to that telnet window.
I have embedded 'plink.exe' as an "Object 7" in Sheet1. below is the code which copies this object and paste created of today's date in temp folder:
EmbeddedObject.Copy
Set oFolder = CreateObject("Shell.Application").Namespace(sFolder & Chr(0))
oFolder.Self.InvokeVerb "Paste"
Here the problem is after copy-paste, the file is showing as corrupted. I tried adding a zip file, but zip also gets corrupted.
So I had added a code to open the object within Excel and using SendKeys and 7z Extractor I extract to temp folder again relying on SendKeys.
Please help me with to copy it in better way without getting file corrupted.
Here is my code.
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function EmptyClipboard Lib "user32" () As Long
Private Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hWnd As LongPtr) As LongPtr
Private Declare PtrSafe Function CloseClipboard Lib "user32" () As Long
#Else
Private Declare Function EmptyClipboard Lib "user32" () As Long
Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32" () As Long
#End If
Private Type FUNC_OUT_RESULTS
SUCCESS As Boolean
SAVED_FILE_PATH_NAME As String
ERROR As String
End Type
Sub test()
Dim tRes As FUNC_OUT_RESULTS
Dim oleObj As OLEObject
tRes = SaveEmbeddedOleObjectToDisk _
(EmbeddedObject:=ActiveSheet.OLEObjects("Object 7"), FilePathName:="C:\Users\user\AppData\Local\Temp\20170512\")
With tRes
If .SUCCESS Then
MsgBox "OleObject successfully saved as : '" & .SAVED_FILE_PATH_NAME & " '", vbInformation
Else
MsgBox .ERROR, vbCritical
End If
End With
End Sub
Private Function SaveEmbeddedOleObjectToDisk( _
ByVal EmbeddedObject As OLEObject, _
ByVal FilePathName As String _
) _
As FUNC_OUT_RESULTS
Dim oFolder As Object
Dim sFolder As String
On Error GoTo errHandler
If Len(Dir$(FilePathName)) <> 0 Then 'Err.Raise 58
Dim FSO As Object
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefile FilePathName & "\*.*", True 'Delete files
FSO.deletefolder FilePathName 'Delete Todays Date folder
MkDir FilePathName 'Make Todays Date folder
End If
'\---------------------------------------\
sFolder = Left$(FilePathName, InStrRev(FilePathName, "\") - 10)
If Len(Dir$(sFolder, vbDirectory)) = 0 Then
MkDir sFolder
End If
If EmbeddedObject.OLEType = xlOLEEmbed Then
EmbeddedObject.Verb Verb:=xlPrimary '\---Here it opens within excel
Set EmbeddedObject = Nothing
Application.DisplayAlerts = True
Dim oShell
Set oShell = CreateObject("WScript.Shell")
Application.Wait (Now + TimeValue("0:00:02"))
oShell.AppActivate sFolder & "\plink*"
oShell.SendKeys "{F5}" '\----it extracts to temp-----------\
oShell.SendKeys FilePathName
oShell.SendKeys "{ENTER}"
Application.Wait (Now + TimeValue("0:00:01"))
oShell.AppActivate sFolder & "\plink*"
oShell.SendKeys ("%{F4}")
'----Copy the object without opening-----
' EmbeddedObject.Copy
' Set oFolder = CreateObject("Shell.Application").Namespace(sFolder & Chr(0))
' oFolder.Self.InvokeVerb "Paste"
'\---------------------------------------\
SaveEmbeddedOleObjectToDisk.SAVED_FILE_PATH_NAME = FilePathName
SaveEmbeddedOleObjectToDisk.SUCCESS = True
End If
Call CleanClipBoard
Exit Function
errHandler:
SaveEmbeddedOleObjectToDisk.ERROR = Err.Description
Call CleanClipBoard
End Function
Private Function GetPastedFile( _
ByVal Folder As String _
) _
As String
Dim sCurFile As String
Dim sNewestFile As String
Dim dCurDate As Date
Dim dNewestDate As Date
Folder = Folder & "\"
sCurFile = Dir$(Folder & "*.*", vbNormal)
Do While Len(sCurFile) > 0
dCurDate = FileDateTime(Folder & sCurFile)
If dCurDate > dNewestDate Then
dNewestDate = dCurDate
sNewestFile = Folder & sCurFile
End If
sCurFile = Dir$()
Loop
GetPastedFile = sNewestFile
End Function
Private Sub CleanClipBoard()
OpenClipboard 0
EmptyClipboard
CloseClipboard
End Sub

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.

VBA Dialogue FileFilter Partial File Name

I have a directory with several .txt files. Let's say
hi.txt
hello.txt
hello_test.txt
test.txt
Using a file dialogue in VBA, how can I filter to show only "*test.txt" matching files (ie last two) in the dropdown? Or can I only use *. filters?
The following seems it should work but does not:
Sub TestIt()
Dim test As Variant 'silly vba for not having a return type..
test = Application.GetOpenFilename(FileFilter:="test (*test.txt), *test.txt")
End Sub
edit: clarifying in case this wasn't clear: I want to filter "test.txt" instead of ".txt" files so I can only select from hello_test.txt and test.txt in the chooser.
I see that you are concerned about putting text in the file name box, but that is exactly what you need to do and appears to be the norm for your situation. I got hung up on the exact same issue.
This is what I used:
Public Sub Browse_Click()
Dim fileName As String
Dim result As Integer
Dim fs
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select Test File"
.Filters.Add "Text File", "*.txt"
.FilterIndex = 1
.AllowMultiSelect = False
.InitialFileName = "*test*.*"
result = .Show
If (result <> 0) Then
fileName = Trim(.SelectedItems.Item(1))
Me!txtFileLocation = fileName
End If
End With
How about filedialog?
Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogOpen)
With dlgOpen
.AllowMultiSelect = True
.InitialFileName = "Z:\docs\*t*.*x*"
.Show
End With
http://msdn.microsoft.com/en-us/library/aa213120(v=office.11).aspx
Is this what you are trying? Paste this in a module and run the sub OpenMyFile
Private Declare Function GetOpenFileName Lib "comdlg32.dll" Alias _
"GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Sub OpenMyFile()
Dim OpenFile As OPENFILENAME
Dim lReturn As Long
Dim strFilter As String
OpenFile.lStructSize = Len(OpenFile)
'~~> Define your filter here
strFilter = "Text File (*test.txt)" & Chr(0) & "*test.txt" & Chr(0)
With OpenFile
.lpstrFilter = strFilter
.nFilterIndex = 1
.lpstrFile = String(257, 0)
.nMaxFile = Len(.lpstrFile) - 1
.lpstrFileTitle = .lpstrFile
.nMaxFileTitle = .nMaxFile
.lpstrInitialDir = "C:\Users\Siddharth Rout\Desktop\"
.lpstrTitle = "My FileFilter Open"
.flags = 0
End With
lReturn = GetOpenFileName(OpenFile)
If lReturn = 0 Then
'~~> User cancelled
MsgBox "User cancelled"
Else
MsgBox "User selected" & ":=" & OpenFile.lpstrFile
'
'~~> Rest of your code
'
End If
End Sub