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
Related
We use a VBA tool to extract modules, forms and reports from our Access applications and create an executable for users. This tool has been working without any problems until very recently. However, when I use it to extract from a couple of applications, I keep on encountering an "Automation Error (The remote procedure call failed)" error. However, my colleague (running the same code on a virtually identical build) is able to run it ok.
This is running on Win10 Pro (v2004 - 19041.685), Office 2016 Pro Plus (16.0.4266.1001). I believe my colleague's machine should be the same, as we have only just moved across to these laptops.
This is the core code:
Public Sub ExportAll()
On Error GoTo ErrorProc
Dim oAccessApp As Access.Application
Dim oDoc As Document
Dim sFilePath As String
Dim oDb As Database
Dim fso As FileSystemObject
Dim strFile As String
Dim strFolder As String
strFile = "accdb path"
strFolder = oApp.GetFolder(strFile)
Set oAccessApp = oApp.OpenDatabase(strFile)
Set oDb = oAccessApp.CurrentDb
Set fso = New FileSystemObject
If Not fso.FolderExists((strFolder) & "\SCC") Then
fso.CreateFolder strFolder & "\SCC"
End If
If Not fso.FolderExists(strFolder & "\SCC\Modules") Then
fso.CreateFolder strFolder & "\SCC\Modules"
End If
If Not fso.FolderExists(strFolder & "\SCC\Forms") Then
fso.CreateFolder strFolder & "\SCC\Forms"
End If
If Not fso.FolderExists(strFolder & "\SCC\Reports") Then
fso.CreateFolder strFolder & "\SCC\Reports"
End If
For Each oDoc In oDb.Containers("Modules").Documents
DoEvents
sFilePath = strFolder & "\SCC\Modules\" & oDoc.Name & ".bas.txt"
oAccessApp.SaveAsText acModule, oDoc.Name, sFilePath
Next
For Each oDoc In oDb.Containers("Forms").Documents
DoEvents
sFilePath = strFolder & "\SCC\Forms\" & oDoc.Name & ".frm.txt"
oAccessApp.SaveAsText acForm, oDoc.Name, sFilePath
Next
For Each oDoc In oDb.Containers("Reports").Documents
DoEvents
sFilePath = strFolder & "\SCC\Reports\" & oDoc.Name & ".rpt.txt"
oAccessApp.SaveAsText acReport, oDoc.Name, sFilePath
Next
oDb.Close
Set oDb = Nothing
oAccessApp.Quit
Set oAccessApp = Nothing
Exit Sub
ErrorProc:
If Not (oAccessApp Is Nothing) Then
oAccessApp.Quit
End If
Set oAccessApp = Nothing
MsgBox Err.Description, vbExclamation, "Error " & Err.Number
End Sub
As the extraction takes place, the database being extracted should remain open throughout. Each failure occurs in the For Each oDoc In oDb.Containers("Modules").Documents loop, and happens when a particular module is referenced by the oDoc variable. When I step through and reach the offending module, all is fine until the line with oDoc.Name is hit, at which point the database closes and all the messages for the object oDb reads "".
The module causing the problem is below:
Option Compare Database
Option Explicit
'
' Opens file using default program
' (.xls files open in Excel, .doc files open in Word, etc)
'
'Code Courtesy of
'Dev Ashish
#If Win64 Then
Private Declare PtrSafe Function apiShellExecute 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 apiShellExecute 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
Public Enum ShellExecuteWinStyle
WIN_NORMAL = 1 'Open Normal
WIN_MAX = 2 'Open Maximized
WIN_MIN = 3 'Open Minimized
End Enum
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&
'
' Opens file using default program
' (.xls files open in Excel, .doc files open in Word, etc)
'
Function ShellExecute(strFile As Variant, lShowHow As ShellExecuteWinStyle)
#If Win64 Then
Dim lRet As LongPtr
#Else
Dim lRet As Long
#End If
Dim varTaskID As Variant
Dim stRet As String
Dim stFile As String
If IsNull(strFile) Or strFile = "" Then Exit Function
stFile = strFile
'First try ShellExecute
lRet = apiShellExecute(hWndAccessApp, vbNullString, _
stFile, vbNullString, vbNullString, lShowHow)
If lRet > ERROR_SUCCESS Then
stRet = vbNullString
lRet = -1
Else
Select Case lRet
Case ERROR_NO_ASSOC:
'Try the OpenWith dialog
varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
& stFile, WIN_NORMAL)
lRet = (varTaskID <> 0)
Case ERROR_OUT_OF_MEM:
stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
Case ERROR_FILE_NOT_FOUND:
stRet = "Error: File not found. Couldn't Execute!"
Case ERROR_PATH_NOT_FOUND:
stRet = "Error: Path not found. Couldn't Execute!"
Case ERROR_BAD_FORMAT:
stRet = "Error: Bad File Format. Couldn't Execute!"
Case Else:
End Select
End If
ShellExecute = lRet & _
IIf(stRet = "", vbNullString, ", " & stRet)
End Function
I have tried the following:
removing the problem module (process completes successfully)
renaming the module
removing pro-compile conditional statements
moving extraction code to a new database
extracting from database with only problem module plus module with comments
repair MS Office
reinstall MS Office
downgrade Windows updates
Does anyone have any idea why this might be failing? Any suggestions on how to rectify would be really appreciated.
I created a macro for a file and first it was working fine, but today I've been opening and restarting the file and macro hundreds of times and I'm always getting the following error:
Excel VBA Run-time error '13' Type mismatch
I didn't change anything in the macro and don't know why am I getting the error. Furthermore it takes ages to update the macro every time I put it running (the macro has to run about 9000 rows).
ERROR is somewhere "FileData = WHTTP.ResponseBody"
Sub Test2()
Dim A As Long
Dim FileNum As Long
Dim FileData() As Byte
Dim MyFile As String
Dim WHTTP As Object
On Error Resume Next
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5")
If Err.Number <> 0 Then
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
End If
On Error GoTo 0
If Dir("C:\MyDownloads", vbDirectory) = Empty Then MkDir "C:\MyDownloads"
For A = 1 To 228
MyFile = Cells(A, 1).Text
TempFile = Right(MyFile, InStr(1, StrReverse(MyFile), "/") - 1)
WHTTP.Open "GET", MyFile, False
WHTTP.Send
FileData = WHTTP.ResponseBody
FileNum = FreeFile
Open "C:\MyDownloads\" & TempFile For Binary Access Write As #FileNum
Put #FileNum, 1, FileData
Close #FileNum
Next
Set WHTTP = Nothing
MsgBox "Open the folder [ C:\MyDownloads ] for the downloaded file..."
End Sub
Put On Error Resume Next above the line causing an error (probably this line WHTTP.Send). Put this block of code after your line with an error.
Files/Web Addresses/Registry keys - YOU MUST ASSUME IT MAY NOT WORK and trap errors so you know why (and where it's not working). Usually these are not programming questions.
If err.number <> 0 then
ERRString = ErrString & ""
ERRString = ErrString & "Error getting file"
ERRString = ErrString & "=================="
ERRString = ErrString & ""
ERRString = ErrString & "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
ERRString = ErrString & "Source " & err.source
ERRString = ErrString & ""
ERRString = ErrString & "HTTP Error " & WHTTP.Status & " " & WHTTP.StatusText
ERRString = ErrString & WHTTP.getAllResponseHeaders
Msgbox ErrString
End If
Just download direct using API call and URL
Option Explicit
#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
Private Declare PtrSafe Function DeleteUrlCacheEntry Lib "Wininet.dll" _
Alias "DeleteUrlCacheEntryA" ( _
ByVal lpszUrlName As String _
) 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
Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" _
Alias "DeleteUrlCacheEntryA" ( _
ByVal lpszUrlName As String _
) As Long
#End If
Public Const BINDF_GETNEWESTVERSION As Long = &H10
Public Const folderName As String = "C:\Users\User\Desktop\Blah.zip" '<== Change to destination
Public Sub downloadIFolder()
Dim ret As Long
ret = URLDownloadToFile(0, "http://www.bseindia.com/BSEDATA/margins/VAR290716.zip", folderName, BINDF_GETNEWESTVERSION, 0)
MsgBox ret
End Sub
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.
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
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