I am new to coding with VBA. This is my unfinished code to print documents in a folder containing documents with 3 distinct headers, \"DN\" \"INV\" and \"PO\". I\'ve been se
Yo,
I found this: https://www.ozgrid.com/forum/forum/help-forums/excel-general/90407-printing-a-file-using-vba-code
Option Explicit
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
Public Sub PrintFile(ByVal strPathAndFilename As String)
Call apiShellExecute(Application.hwnd, "print", strPathAndFilename, vbNullString, vbNullString, 0)
End Sub
Sub Test()
PrintFile ("C:\Test.pdf")
End Sub
But this only let's you print on your default printer.
I tested it. It works:
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
Public Sub PrintFile(ByVal strPathAndFilename As String)
Call apiShellExecute(Application.hwnd, "print", strPathAndFilename, vbNullString, vbNullString, 0)
End Sub
Sub PrintPDF()
'' To set the path to the current folder
Set shApp = CreateObject("shell.application")
'currentPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
currentPath = Application.ActiveWorkbook.Path
Set shFolder = shApp.Namespace(currentPath)
'' To set the items in the current folder as "files"
Set Files = shFolder.Items()
''Start of code''
'msgbox("Starting Script")
For Each file In Files
If InStr(file, ".pdf") Then
' If name contains "DN" '
If InStr(file, "DN") Then
PrintFile (currentPath + "\" + file)
End If
' if name contains "INV" '
If InStr(file, "INV") Then
For i = 1 To 6
PrintFile (currentPath + "\" + file)
Next i
End If
' if name contains "PO" '
If InStr(file, "PO") Then
PrintFile (currentPath + "\" + file)
PrintFile (currentPath + "\" + file)
End If
End If
Next
MsgBox ("completed")
End Sub
So, after correcting a mistake, that it is VBS and not VBA i suggest this code:
Set shApp = CreateObject("shell.application")
Set shFolder = shApp.Namespace(currentPath)
'' To set the items in the current folder as "files"
Set Files = shFolder.Items()
''Start of code''
For Each file In Files
If InStr(file, ".pdf") Then
' If name contains "DN" '
If InStr(file, "DN") Then
file.InvokeVerbEx("Print")
WScript.Sleep 1000 'wait 1 sec
End If
' if name contains "INV" '
If InStr(file, "INV") Then
Filename = currentPath + "\" + file
Do
i = i+1
file.InvokeVerbEx("Print")
WScript.Sleep 1000 'wait 1 sec
Loop until i >=6
i = 0
End If
' if name contains "PO" '
If InStr(file, "PO") Then
Filename = currentPath + "\" + file
file.InvokeVerbEx("Print")
WScript.Sleep 1000 'wait 1 sec
file.InvokeVerbEx("Print")
WScript.Sleep 1000 'wait 1 sec
End If
End If
Next
MsgBox ("completed")