vba print code example
Example 1: vba printf
Public Function PrintF(ByVal pTemplate As String, ByVal pPattern As String, _
ParamArray pParameters()) As String
Dim lNParam As Long
Dim sSearched As String
Dim sReturn As String
Dim sValues
PrintF = pTemplate
For Each sValues In pParameters
lNParam = lNParam + 1
sSearched = pPattern & lNParam & StrReverse(pPattern)
If InStrB(pTemplate, sSearched) Then PrintF = Replace(PrintF, sSearched, sValues)
Next
End Function
Sub TestMe()
Dim sTemplate As String: sTemplate = "It is |%1%| on |%2%|."
Dim sPattern As String: sPattern = "|%"
Debug.Print PrintF(sTemplate, sPattern, "cold", "Monday")
End Sub
Example 2: how to use print function in excel vba
Sub Print_Example()
Dim strFolder As String
Dim strFile As String
Dim dlgFolder As FileDialog
Dim rng As Range
Set dlgFolder = Application.FileDialog(msoFileDialogFolderPicker)
If dlgFolder.Show = True Then
strFolder = dlgFolder.SelectedItems(1)
Else
Exit Sub
End If
Set rng = Range("A1:D5")
strFile = "Print_Output.txt"
PrintRangeToFile strFolder & "\" & strFile, rng
End Sub
Sub PrintRangeToFile(strFile As String, rng As Range)
Dim row As Range, cell As Range
Dim FileNumber As Integer
FileNumber = FreeFile
Open strFile For Output As #FileNumber
For Each row In rng.Rows
For Each cell In row.Cells
If cell.Column = row.Cells.Count Then
Print #FileNumber, cell
Else
Print #FileNumber, cell,
End If
Next cell
Next row
Close #FileNumber
End Sub