I'm having problems with the below code.
I have incorporated it into the Code Window commandbar which simply calls PrintProcedure.
The call is working fine, it's just that whenever I right click over a VBA procedure I want to print and select the "Print this procedure" entry (which calls PrintProcedure), Notepad opens up and always complains:
Cannot find the [full path and filename] file. Do you want to create a new file?
However, if I set a break point in PrintProcedure, call it as above and then step through it I don't get the complaint. Can anyone suggest what I'm doing wrong?
Option Explicit
Public 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
Public Sub PrintProcedure()
Dim objModule As CodeModule, objPane As CodePane
Dim lngStartLine As Long, lngEndLine As Long
Dim lngStartCol As Long, lngEndCol As Long
Dim lngCountLines As Long
Dim strProcName As String, strPath As String
Dim intCount As Integer
Dim lngN As Long, FileNum As Long
Set objPane = Application.VBE.ActiveCodePane
Set objModule = objPane.CodeModule
' get current selection
objPane.GetSelection lngStartLine, lngStartCol, lngEndLine, lngEndCol
' get procedure name
strProcName = objModule.ProcOfLine(lngStartLine, vbext_pk_Proc)
' get first line of procedure
lngStartLine = objModule.ProcBodyLine(strProcName, vbext_pk_Proc)
' count lines
lngCountLines = objModule.ProcCountLines(strProcName, vbext_pk_Proc)
' get output file name
strPath = Application.VBE.ActiveVBProject.fileName & "_" & strProcName & "_temp.txt"
If strPath <> "False" Then
' write to file
FileNum = FreeFile
Open strPath For Output As #FileNum
Print #FileNum, objModule.Lines(lngStartLine, lngCountLines)
Close #FileNum
End If
ShellExecute 0, "Print", strPath, "", "", 1
Kill (strPath)
End Sub
Bookmarks