Difficulites in accessing the Download files dialog box - VBA Code - vba

I have mini project in VBA (Excel). I need to open the IE and download the files (save the doc) in the designated folder in my desktop.
However, I having difficulties in accessing the Download files dialog box. Even tried Savekeys concept but in vain.
How to proceed further and save the files?
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
Sub DownloadFileFromWeb()
Dim myFile As String
Dim strSavePath As String
Dim URL As String, ext As String
URL = "www.ahma.org/Education/BRD_Hardlines_Industry_Item.doc" 'for TEST
strSavePath = "C:\Users\Yogendra.Ur\Desktop\" & "DownloadedFile" & ext
Dim buf, Ret As Long
buf = Split(URL, ".")
ext = buf(UBound(buf))
Dim IE As Object
Set IE = CreateObject("internetexplorer.application")
IE.VISIBLE = True
IE.Navigate URL
Ret = URLDownloadToFile(0, URL, strSavePath, 0, 0)
If Ret = 0 Then
MsgBox "Download has been succeed!"
Else
MsgBox "Error"
End If
End Sub

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
Sub DownloadFileFromWeb()
Dim myFile As String
Dim buf, Ret As Long
Dim strSavePath As String
Dim URL As String, ext As String
URL = "http://www.ahma.org/Education/BRD_Hardlines_Industry_Item.doc"
buf = Split(URL, ".")
ext = buf(UBound(buf))
strSavePath = "C:\local files\DownloadedFile." & ext
Debug.Print strSavePath
Ret = URLDownloadToFile(0, URL, strSavePath, 0, 0)
If Ret = 0 Then
MsgBox "Download OK!"
Else
MsgBox "Error"
End If
End Sub

Related

Print_All_PDF_Files_in_Folder()

I've been using this code to print PDFs from a folder at work but the code isn't working anymore. I'm working remotely from home and I've updated the file path and I still receive a run time 53 error code. Can anyone help?
Public Sub Print_All_PDF_Files_in_Folder()
Dim folder As String
Dim PDFfilename As String
folder = "C:\Users\16468\Desktop\CONF\TAXES" 'CHANGE AS REQUIRED
If Right(folder, 1) <> "\" Then folder = folder & "\"
PDFfilename = Dir(folder & "*.pdf", vbNormal)
While Len(PDFfilename) <> 0
Print_PDF folder & PDFfilename
PDFfilename = Dir() ' Get next matching file
Wend
End Sub
Private Sub Print_PDF(sPDFfile As String)
Shell "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe /p /h " & Chr(34) & sPDFfile & Chr(34), vbNormalFocus
End Sub
This Should print just about anything:
Option Explicit
#If VBA7 Then
Private Declare PtrSafe Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As LongPtr, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As LongPtr
#Else
Private Declare Function ShellExecute _
Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long
#End If
Private Const SW_HIDE = 0
Sub FilePrint(ByVal strFilePath As String)
Dim retVal As Long
retVal = ShellExecute(0, "Print", strFilePath, 0, 0, SW_HIDE)
If retVal < 32 Then
'// there are Error codes for this..left out
MsgBox "An Error occured...could not print"
End If
End Sub
Public Sub Print_All_PDF_Files_in_Folder()
Dim folder As String
Dim PDFfilename As String
folder = "C:\Users\16468\Desktop\CONF\TAXES" 'CHANGE AS REQUIRED
If Right(folder, 1) <> "\" Then folder = folder & "\"
PDFfilename = Dir(folder & "*.pdf", vbNormal)
While Len(PDFfilename) <> 0
FilePrint folder & PDFfilename
PDFfilename = Dir() ' Get next matching file
Wend
End Sub
Original Code found here

how to solve error when downloading images using vba?

I tried to download the image from the URL and it worked normally.
but if it is run on a 64 bit computer then an error message
"Compile error in hidden module: Module 10.
This error commonly occurs when code is incompatible with the version,platform"
I don't know what to do, any ideas?
this is my code
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 Download()
Dim strPath As String
Dim FolderName As String
Dim x As Integer
Dim i As Long
Dim sData As Worksheet: Set sData = Sheets("Sheet17")
Application.DisplayAlerts = False
FolderName = "C:\Try"
With sData
For i = 1 To 100
For x = 5 To 12
Application.Calculation = xlCalculationManual
If Sheet17.Cells(i, x).Value <> "" Then
strPath = FolderName & "\" & i & "-" & x - 4 & ".jpg"
Ret = URLDownloadToFile(0, Sheet17.Cells(i, x).Value, strPath, 0, 0)
End If
Next x
Next i
Application.Calculation = xlCalculationAutomatic
End With
Application.DisplayAlerts = True
End Sub

Open only one instance of a text file

In VBA, I have a function that opens a text file. This allows me to place a button on a form and have it show a file when clicked.
The function works fine, however the aforementioned button is clicked multiple times, it will open the same document over and over, rather than just the once.
How can I make it so that a file is only opened once?
Sub OpenTextFile(ByVal filePath As String)
If Len(Dir(filePath)) = 0 Then Exit Sub ' Ensure that the file to open actaully exists
Dim txtFile As Variant
txtFile = Shell("C:\WINDOWS\notepad.exe " & filePath, 1)
End Sub
First check if a Shell ID has previously been assigned to the Workbooks .CustomDocumentProperties property. If it has, then we need to check if that Shell ID instance is still open. We can do that by using the Shell ID and passing it into the WHERE clause of a query against Win32_Process.
If there is no Shell ID assigned to the property, we can go straight to opening the text file. Once we open the text file, we update the .CustomDocumentProperties Property with the new text file Shell ID.
Option Explicit
Sub OpenTextFile()
Dim filePath As String
Dim txtFile As Long
Dim txtOpenCount As Integer
Dim wb As Workbook
Dim wmiService As Object, winQry As Object
Set wb = ThisWorkbook
On Error Resume Next
txtFile = CLng(wb.CustomDocumentProperties("txtFileNum"))
If Err.Number = 0 Then '' If CustomDocumentProperty returned _
without an error then use this to close txt file.
Set wmiService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& ".\root\cimv2")
Set winQry = wmiService.ExecQuery _
("SELECT * from Win32_Process WHERE ProcessID = " & txtFile)
txtOpenCount = winQry.Count
End If
On Error GoTo 0
If txtOpenCount = 0 Then '' If the txtFile is not found, then open.
filePath = "F:\test.txt"
If txtFile > 0 Then
wb.CustomDocumentProperties("txtFileNum").Delete
End If
txtFile = Shell("C:\WINDOWS\notepad.exe " & filePath, vbNormalFocus)
'' Update CustomDocumentProperty with the new txtFile number.
wb.CustomDocumentProperties.Add Name:="txtFileNum", _
Value:=txtFile, _
LinkToContent:=False, _
Type:=msoPropertyTypeString
End If
End Sub
If you are in Access, you can take advantage of the .CreateProperty method, and then the .Properties.Append method. You have to pass the property created from .CreateProperty into the .Properties.Append method. Updated code below.
Option Explicit
Sub OpenTextFile()
Dim filePath As String
Dim txtFile As Long, oTxt As Object
Dim txtOpenCount As Integer
Dim db As Database
Dim wmiService As Object, winQry As Object
Set db = CurrentDb
On Error Resume Next
txtFile = db.Properties("txtFileNum").Value
If Err.Number = 0 Then '' If CustomDocumentProperty returned _
without an error then use this to close txt file.
Set wmiService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& ".\root\cimv2")
Set winQry = wmiService.ExecQuery _
("SELECT * from Win32_Process WHERE ProcessID = " & txtFile)
txtOpenCount = winQry.Count
End If
On Error GoTo 0
If txtOpenCount = 0 Then '' If the txtFile is not found, then open.
filePath = "F:\test.txt"
If txtFile > 0 Then
db.Properties.Delete "txtFileNum"
End If
txtFile = Shell("C:\WINDOWS\notepad.exe " & filePath, vbNormalFocus)
'' Update db Properties with the new txtFile number.
Set oTxt = db.CreateProperty("txtFileNum", dbLong, txtFile, False)
db.Properties.Append oTxt
End If
End Sub
If you need it. Here is a function to see if notepad is running.
Declare these up top.
Private Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" ( _
ByVal hObject As Long) As Long
Private Declare Function EnumProcesses Lib "PSAPI.DLL" ( _
lpidProcess As Long, ByVal cb As Long, cbNeeded As Long) As Long
Private Declare Function EnumProcessModules Lib "PSAPI.DLL" ( _
ByVal hProcess As Long, lphModule As Long, ByVal cb As Long, lpcbNeeded As Long) As Long
Private Declare Function GetModuleBaseName Lib "PSAPI.DLL" Alias "GetModuleBaseNameA" ( _
ByVal hProcess As Long, ByVal hModule As Long, ByVal lpFileName As String, ByVal nSize As Long) As Long
Private Const PROCESS_VM_READ = &H10
Private Const PROCESS_QUERY_INFORMATION = &H400
Then send this the process name. b = IsProcessRunning("notepad.exe")
Private Function IsProcessRunning(ByVal sProcess As String) As Boolean
'Check to see if a process is currently running
Const MAX_PATH As Long = 260
Dim lProcesses() As Long
Dim lModules() As Long
Dim N As Long
Dim lRet As Long
Dim hProcess As Long
Dim sName As String
sProcess = UCase$(sProcess)
ReDim lProcesses(1023) As Long
If EnumProcesses(lProcesses(0), 1024 * 4, lRet) Then
For N = 0 To (lRet \ 4) - 1
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, lProcesses(N))
If hProcess Then
ReDim lModules(1023)
If EnumProcessModules(hProcess, lModules(0), 1024 * 4, lRet) Then
sName = String$(MAX_PATH, vbNullChar)
GetModuleBaseName hProcess, lModules(0), sName, MAX_PATH
sName = Left$(sName, InStr(sName, vbNullChar) - 1)
If sProcess = UCase$(sName) Then
IsProcessRunning = True
Exit Function
End If
End If
End If
CloseHandle hProcess
Next N
End If
End Function

Downloading a PDF

I am trying to download a .pdf file which opens up in an IE Web browser. Here is my code:
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
Sub DownPDF()
Dim sUrl As String
Dim sPath As String
sPath = "C:\Users\adhil\Documents"
sUrl = "http://analytics.ncsu.edu/sesug/2010/HOW01.Waller.pdf"
Ret = URLDownloadToFile(0, sUrl, sPath, 0, 0)
If Ret = 0 Then
Debug.Print sUrl & " downloaded to " & sPath
Else
Debug.Print sUrl & " not downloaded"
End If
End Sub
However, I am unable to get the file downloaded although response says so.
Can anyone assist me?
The function expects the parameter szFileName to be a fullpath name of a file, not a folder.
Try with this:
sPath = "C:\Users\adhil\Documents\HOW01.Waller.pdf"
I worked with me, while it did not work when the destination file name was omitted.

Excel Macro code to connect to a FTPS server i.e. FTP Over SSL not FTP server

Problem description:
Unable to connect to a FTPS server , this is a private server FTP Over SSL or FTPS. It is a secure connection same as HTTPS. .The code I am using is successful to connect to a public server . But it seems in order to connect to a secured FTPS server I need to use some sort of SSL encryption . I have no idea at all , I am java guy but I am asked to fix this , it is always fun to learn new things , and this time its VBA code, . Please help me VBA experts.
Can somebody please tell me what and where is the code I should modify or add in order to connect to my FTPS server . Please note again I can connect to FTP server but not FTPS.
Below is the code I am currently using. This will be a great help thank you!
'API code
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Const MAX_PATH = 260
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type
Private Declare Function InternetOpen _
Lib "wininet.dll" _
Alias "InternetOpenA" _
(ByVal sAgent As String, _
ByVal lAccessType As Long, _
ByVal sProxyName As String, _
ByVal sProxyBypass As String, _
ByVal lFlags As Long) As Long
'Connect to the network
Private Declare Function InternetConnect _
Lib "wininet.dll" _
Alias "InternetConnectA" _
(ByVal hInternetSession As Long, _
ByVal sServerName As String, _
ByVal nServerPort As Integer, _
ByVal sUsername As String, _
ByVal sPassword As String, _
ByVal lService As Long, _
ByVal lFlags As Long, _
ByVal lContext As Long) As Long
'Get a file using FTP
Private Declare Function FtpGetFile _
Lib "wininet.dll" _
Alias "FtpGetFileA" _
(ByVal hFtpSession As Long, _
ByVal lpszremoteDir As String, _
ByVal lpszNewFile As String, _
ByVal fFailIfExists As Boolean, _
ByVal dwFlagsAndAttributes As Long, _
ByVal dwFlags As Long, _
ByVal dwContext As Long) As Boolean
'Close the Internet object
Private Declare Function InternetCloseHandle _
Lib "wininet.dll" _
(ByVal hInet As Long) As Integer
'
Private Declare Function FtpFindFirstFile _
Lib "wininet.dll" _
Alias "FtpFindFirstFileA" _
(ByVal hFtpSession As Long, _
ByVal lpszSearchFile As String, _
lpFindFileData As WIN32_FIND_DATA, _
ByVal dwFlags As Long, _
ByVal dwContent As Long) As Long
Private Declare Function InternetFindNextFile Lib "wininet.dll" Alias "InternetFindNextFileA" _
(ByVal hFind As Long, lpvFindData As WIN32_FIND_DATA) As Long
Private Declare Function FtpSetCurrentDirectory Lib "wininet.dll" Alias "FtpSetCurrentDirectoryA" _
(ByVal hConnect As Long, ByVal lpszDirectory As String) As Long
'***************
'downloadFile method downloads files from a specified server through FTP
'This method downloads files on only first level of specified directory on the server
'
'
'
'
'***************
'***************
'To do
'
'1. if localDir does not include "\", it does not work - fixed
'2. if folders exist on the remote server, it will not download
'
'
'***************
'download files from a specified server
Public Function downloadFiles(ServerName As String, UserName As String, Password As String, remoteDir As String, localDir As String, logFile As String) As Variant()
Dim INet As Long
Dim INetConn As Long
Dim RetVal As Long
Dim Success As Long
Dim hFile As Long
Dim w32FindData As WIN32_FIND_DATA
Dim StrFile As String
Dim fileList() As String
Dim cnt As Long
Dim gcnt As Long
Dim i As Integer
Dim curDir As Long
Dim result(1) As Variant
cnt = -1
gcnt = 0
RetVal = False
Rem confirm local dir has \ at the end
If Not Right(localDir, 1) = "\" Then
localDir = localDir + "\"
End If
'Test Code need to remove as the username and password are hardcoded
INet = InternetOpen("MYFTP Control", 1&, vbNullString, vbNullString, 0&)
If INet > 0 Then
INetConn = InternetConnect(INet, ServerName, 0&, UserName, Password, 1&, 0&, 0&)
If INetConn > 0 Then
file.log "==== Connected to " & ServerName & "===", logFile
curDir = FtpSetCurrentDirectory(INetConn, remoteDir)
If (curDir <> 0) Then
file.log "current remote dir: " & remoteDir, logFile
End If
''''''''''''''''''''
''Create a list of files to download
''''''''''''''''''''
'get file list
hFile = FtpFindFirstFile(INetConn, remoteDir, w32FindData, INTERNET_FLAG_RELOAD, 0&)
'create a list of files on the remote server
If hFile = 0 Then
file.log "cannot get a list of files", logFile
Else
Do
StrFile = Left(w32FindData.cFileName, InStr(w32FindData.cFileName, vbNullChar) - 1)
StrFile = Mid(StrFile, InStrRev(StrFile, " ") + 1)
'if the path is directory, skip this
If ((w32FindData.dwFileAttributes And &H10) <> &H10) Then
'strFile = strFile & "/"
cnt = cnt + 1
ReDim Preserve fileList(cnt)
fileList(cnt) = StrFile
Debug.Print StrFile 'Debug
End If 'end of skiping dir condition
Loop Until InternetFindNextFile(hFile, w32FindData) = 0
''''''''''''''''''''
''Download files on the list
''''''''''''''''''''
For i = 0 To cnt
'set local file
StrFile = localDir & fileList(i)
'download a file
Success = FtpGetFile(INetConn, fileList(i), StrFile, False, FILE_ATTRIBUTE_NORMAL, BINARY_TRANSFER, 0&)
If Success > 0 Then
file.log fileList(i) & " is downloaded", logFile
gcnt = gcnt + 1
Else
file.log fileList(i) & " is Not downloaded", logFile
End If
Next
End If
RetVal = InternetCloseHandle(INet)
Else
'cannot connet to the server error message
file.log "Client cannnoot connet to " & ServerName, logFile
RetVal = InternetCloseHandle(INet)
End If
End If
result(0) = cnt + 1
result(1) = gcnt
file.log ServerName & " - " & "Downloaded files: " & CStr(result(1)) & " out of " & CStr(result(0)), logFile
If RetVal > 0 Then
file.log "===Connection is closed===", logFile
Else
file.log "===Connection is not closed correctly===", logFile
End If
downloadFiles = result
End Function
Private Function log(warnLevel As String, info As String, fileName As String)
End Function
Private Function msg(info As String)
MsgBox info
End Function
WinSCP will support FTPS (explicit or implicit); you can use VBA to interface with WinSCP via the latter's scripting commands.
These links should get you started:
https://winscp.net/eng/docs/ftps
https://winscp.net/eng/docs/scripting
https://stackoverflow.com/a/35644297/5472502