Reference controls on a form from a function/sub - vb.net

I have a strong suspicion that what I'm wanting to do is not possible, but I could use the confirmation.
I have a Class Library that I have created to handle some common Subs & Functions that I use a lot (in some form or fashion).
Some of those Subs & Functions can take a go long while (typically in cases where records are being iterated through & processed in some fashion). In those instances I usually have had the function update a progress window (text and stepping a progress bar).
Now that I'm genericizing to put them in the class library I obviously can't anticipate a specific form or control being there. But I'd like to retain the functionality. So what I'm hoping to do is create optional input variables for the RichTextBox & ProgressBar that would be getting updated, so that I can then pass in references to the controls that should be used for statusing.
Is this possible? If so, how? When I try to define any inputs as Windows.Forms.<anything> Intellisense drops out (strongly hinting that I can't type them as controls).
Thanks!
UPDATE: The function I'm trying to add the references to follows, errors are indicated for either System.Windows.Forms.<X>
Public Function ResOut(ByVal D As DataTable, ByVal epath As String, ByVal SAName As String, ByVal Parent As String, ByRef PBar As System.Windows.Forms.ProgressBar, _
ByRef RTB As System.Windows.Forms.RichTextBox) As String
'
Dim res As String = ""
Dim E As New Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim x As Long = 0
Dim f As Long = 1
Dim s As New JMLib.Status
Dim Rng As Microsoft.Office.Interop.Excel.Range
'Define the range
Rng = ws.Range("A1:" & ColNumToStr(D.Columns.Count, epath) & D.Rows.Count)
'Create the array
Dim OArr(D.Rows.Count, x) As Object
'Create a workbook for the data and capture the workbook and sheet for ease of reference
Try
wb = E.Workbooks.Add
ws = wb.Worksheets(1)
Catch ex As Exception
res = "Encountered an error while creating the new workbook to export the results to. No data can be returned."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
'Fill in headers
If res = "" Then
Try
For Each c As DataColumn In D.Columns
ws.Range("A1").Offset(0, x).Value = c.ColumnName
x = x + 1
Next
Catch ex As Exception
res = "Encountered an error while filling in the column headers. This will prevent any data from being returned."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
'Setup the step & frequency for the Step Progress bar
'Dim t() As Long = s.StatSetup(QR.Rows.Count, 58, "Query Runner\ResOut\" & QName, Replace(My.Settings.EPath, "<user>", Environment.UserName) & DStamp() & " Query Scheduler Log.txt")
'f = t(0)
'SProg.Step = t(1)
'Convert the datatable to a 2D array
If res = "" Then
Try
'Fill it
x = 0
For r As Long = 0 To D.Rows.Count - 1 Step 1
Dim dr As DataRow = D.Rows(r)
For c As Integer = 0 To D.Columns.Count - 1 Step 1
OArr(r, c) = dr.Item(c)
Next
x = x + 1
Next
Catch ex As Exception
res = "Encountered an error while outputing the " & x + 1 & "-th record of " & D.Rows.Count & ". No data will be output."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
'output the array to the target range
If res = "" Then
Try
Rng.Value = OArr
'Save the workbook
wb.SaveAs(SAName)
wb.Close(SaveChanges:=False)
Catch ex As Exception
res = "Encountered an error during the export of the results. Some data may have been exported. Review the contents of the Excel workbook that will be visible following this message for more" _
& " details."
E.Visible = True
wb.Activate()
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
Else
'Close the workbook without saving
wb.Close(SaveChanges:=False)
End If
'Cleanup the application
Try
E.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(E)
E = Nothing
wb = Nothing
ws = Nothing
s = Nothing
Rng = Nothing
OArr = Nothing
f = Nothing
x = Nothing
Catch ex As Exception
EL.AddErr("Encountered an error while cleaning up the resources used in JMLib\ResOut. ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
Return res
End Function

I did this by adding references to the progress bar/text box to the Class.
When the class invoked you can set the references or not.
In the class if the reference ISNOT NOTHING I update the progress bar/textbox.
Nothing specific about being in a user written class - here is an example from some library code:
Sub DisplayParcels(aAPNs() As String,...., Optional ProgBar As ProgressBar = Nothing)
...
If ProgBar IsNot Nothing Then
ProgBar.Maximum = aAPNs.Length
ProgBar.Value = 0
ProgBar.Visible = True
End If
...
For Each sAPN In aAPNs
...
If ProgBar IsNot Nothing Then ProgBar.Value = iCnt
Next
...
If ProgBar IsNot Nothing Then ProgBar.Visible = False
End Sub

Related

Sharepoint version history in document via vba?

Here is my problem:
Duplicate versions
I checked the version history on the Sharepoint site and it doesn't show any duplicates.
Here is the code im using:
Sub versionhistory()
'
' versionhistory Macro
On Error Resume Next
' On Error GoTo message
Dim dlvVersions As Office.DocumentLibraryVersions
Dim dlvVersion As Office.DocumentLibraryVersion
Dim strVersionInfo As String
Set dlvVersions = ThisDocument.DocumentLibraryVersions
'MsgBox ActiveDocument.Bookmarks.Count
Dim tbl As Word.Table
'Set tbl = ActiveDocument.Tables.Item(2)
Set tbl = ActiveDocument.Bookmarks("VersionTable").Range.Tables(1)
If dlvVersions.IsVersioningEnabled Then
strVersionInfo = "This document has " & dlvVersions.Count & " versions: " & vbCrLf
Call InsertVersionHistory(tbl, dlvVersions)
For Each dlvVersion In dlvVersions
strVersionInfo = strVersionInfo & _
" - Version #: " & dlvVersion.Index & vbCrLf & _
" - Modified by: " & dlvVersion.ModifiedBy & vbCrLf & _
" - Modified on: " & dlvVersion.Modified & vbCrLf & _
" - Comments: " & dlvVersion.Comments & vbCrLf
Next
Else
strVersionInfo = "Versioning not enabled for this document."
End If
'MsgBox strVersionInfo, vbInformation + vbOKOnly, "Version Information"
Set dlvVersion = Nothing
Set dlvVersions = Nothing
Call GetUserName
'message:
'MsgBox Err.Description
MsgBox ("Insert Version Number in the Header and type a Title in the [Insert Title here] on the front page. It will be automatically updated in the footer." & vbNewLine & vbNewLine & "Do Not Type in the Review and Version tables.")
End Sub
Private Function InsertVersionHistory(oVerTbl As Word.Table, oVersions As Office.DocumentLibraryVersions)
Dim rowIndex As Integer
Dim oVersion As Office.DocumentLibraryVersion
Dim oNewRow As Row
'test
Dim versionIndex As Integer
For rowIndex = 2 To oVerTbl.Rows.Count
oVerTbl.Rows.Item(2).Delete
Next rowIndex
rowIndex = 1
'test
versionIndex = oVersions.Count
For Each oVersion In oVersions
If (rowIndex > 5) Then
Return
End If
rowIndex = rowIndex + 1
oVerTbl.Rows.Add
Set oNewRow = oVerTbl.Rows(oVerTbl.Rows.Count)
oNewRow.Shading.BackgroundPatternColor = wdColorWhite
oNewRow.Range.Font.TextColor = wdBlack
oNewRow.Range.Font.Name = "Tahoma"
oNewRow.Range.Font.Bold = False
oNewRow.Range.Font.Size = 12
oNewRow.Range.ParagraphFormat.SpaceAfter = 4
With oNewRow.Cells(1)
'.Range.Text = oVersion.Index
.Range.Text = versionIndex
End With
With oNewRow.Cells(2)
.Range.Text = FormUserFullName(GetUserFullName(oVersion.ModifiedBy))
End With
With oNewRow.Cells(3)
.Range.Text = oVersion.Modified
End With
With oNewRow.Cells(4)
.Range.Text = oVersion.Comments
End With
versionIndex = versionIndex - 1
Next
Set oVersion = Nothing
End Function
Function GetUserFullName(userName As String) As String
Dim WSHnet, UserDomain, objUser
Set WSHnet = CreateObject("WScript.Network")
'UserDomain = WSHnet.UserDomain
'Set objUser = GetObject("WinNT://" & UserDomain & "/" & userName & ",user")
userName = Replace(userName, "\", "/")
Set objUser = GetObject("WinNT://" & userName & ",user")
'MsgBox objUser.FullName
GetUserFullName = objUser.FullName
End Function
Function FormUserFullName(userName As String) As String
Dim arrUserName As Variant
Dim changedUserName As String
arrUserName = Split(userName, ",")
Dim length As Integer
length = UBound(arrUserName) - LBound(arrUserName) + 1
If length >= 2 Then
changedUserName = arrUserName(1) & " " & arrUserName(0)
Else
changedUserName = userName
End If
FormUserFullName = changedUserName
End Function
Private Function GetUserName()
Dim userName As String
userName = ActiveDocument.BuiltInDocumentProperties("Author")
ActiveDocument.BuiltInDocumentProperties("Author") = FormUserFullName(userName)
End Function
I know this is old, but I was looking for the same thing and found this article. I'm still trying it out, but wanted to share before I got distracted with my real job.
From: SixSigmaGuy on microsoft.public.sharepoint.development-and-programming.narkive.com/...
Wanted to share my findings, so far. Surprisingly, I could not find
anything in the SharePoint Designer object/class that supported versions,
but the Office, Word, Excel, and PowerPoint objects do support it.. It
wasn't easy to find, but once I found it, it works great, as long as the
file in the document library is one of the Office documents.
Here's some sample code, written in Excel VBA, showing how to get the
version information for a paritcular SharePoint Document Library file
created in Excel:
Public viRow As Long
Function fCheckVersions(stFilename As String) As Boolean
' stFilename is the full URL to a document in a Document Library.
'
Dim wb As Excel.Workbook
Dim dlvVersions As Office.DocumentLibraryVersions
Dim dlvVersion As Office.DocumentLibraryVersion
Dim stExtension As String
Dim iPosExt As Long
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 1) = stFilename
If Workbooks.CanCheckOut(stFilename) = True Then
Set wb = Workbooks.Open(stFilename, , True)
Set dlvVersions = wb.DocumentLibraryVersions
If dlvVersions.IsVersioningEnabled = True Then
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 3) = "Num
Versions = " & dlvVersions.Count
For Each dlvVersion In dlvVersions
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 4) = "Version: " & dlvVersion.Index
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 5) = "Modified Date: " & dlvVersion.Modified
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 6) = "Modified by: " & dlvVersion.ModifiedBy
ThisWorkbook.Worksheets("Sheet1").Cells(viRow, 7) = "Comments: " & dlvVersion.Comments
viRow = viRow + 1
Next dlvVersion
End If
wb.Close False
End If
Set wb = Nothing
DoEvents
End Function`
Fortunately, I discovered that Excel can open non-Excel files in most
cases. I.e., I can, for example, open a jpg file in Excel and use the
dlvVersions collection for that file.

Application.Run with Error Trapping

In Access, using VBA, I want to use Application.Run and trap any errors. Unfortunately, Application.Run seems to hijack error trapping. Is there a way to fix this?
On Error Resume Next
Application.Run ...
I never get past Application.Run on an error, even if I specify On Error Resume Next or On Error GoTo ErrCatch. My error trapping setting is ignored.
If the procedure you're calling is inside your VBA project, then you can just call the procedure directly with:
Sub Foo()
'Application.Run "SomeProc"
SomeProc
End Sub
If you need to be able to call things dynamically by name, you could explore using classes and CallByName:
'In a standard module
Sub Foo()
Dim o as New ProcRunner
CallByName o, "SomeProc", VbMethod, args
End Sub
'In a class module called ProcRunner
Sub SomeProc()
DoSomethingHere
'Or, do something in a standard module
Module1.SomeOtherProc
End Sub
Or, you could write your own dynamic handler, along the lines of:
Sub AppRun(ProcName As String, ParamArray Args)
Select Case ProcName
Case "SomeProc"
SomeProc
Case "SomeFunc"
SomeFunc
End Select
End Sub
If you're calling procedures in another VBA project, you may need to add a reference to that project, depending upon the VBA host.
However, if you're using Application.Run because you're calling functions registered by a DLL or XLL, then you don't have any option other than to use Application.Run
There is a way to do this. We have a test harness in VBA and need a way of testing whether a procedure throws an error or not, giving a true/false result. We want True to indicate that an error was thrown, and False to indicate that no error was thrown. This only works for public procedures, but you can pass in a variable amount of arguments.
mIsErrorThrownDuringRunProcedure allows you to pass in a proc name and a varags list of arguments. It creates a new module, then writes another procedure to a the new module, calls that other procedure, and returns the result. The other procedure checks whether running the proc with the given args had any errors. When the dynamically created procedure is finished running, the new module is deleted.
An auxiliary function called mCreateCodeToExecute creates the code that is run from the new module to actually get the true/false result.
Public Function mIsErrorThrownDuringRunProcedure(pProcName As String, ParamArray pArgs() As Variant) As Boolean
Dim lVbComp As Object
Set lVbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
Dim lProcNameToExecute As String
lProcNameToExecute = "mIsErrroRunDuringProcedure" & pProcName
Dim lCodeToExecute As String
Dim lNumArgs As Integer: lNumArgs = 0
Dim lArg As Variant
For Each lArg In pArgs
lNumArgs = lNumArgs + 1
Next
lCodeToExecute = mCreateCodeToExecute(pProcName, lProcNameToExecute, lNumArgs)
lVbComp.CodeModule.AddFromString lCodeToExecute
mIsErrorThrownDuringRunProcedure = Application.Run(lProcNameToExecute, pArgs)
ThisWorkbook.VBProject.VBComponents.Remove lVbComp
End Function
Private Function mCreateCodeToExecute(pProcName As String, lProcNameToExecute As String, numArgs As Integer)
Dim lCodeToExecute As String
lCodeToExecute = "Function " & lProcNameToExecute & "("
lCodeToExecute = lCodeToExecute & "ParamArray pArgs() As Variant) As Boolean" & vbCrLf
Dim lGoToLabel As String: lGoToLabel = "gtCodeHadError"
lCodeToExecute = lCodeToExecute & " On Error GoTo " & lGoToLabel & vbCrLf
lCodeToExecute = lCodeToExecute & " Call " & pProcName & "("
Dim lIndex As Integer
lIndex = 0
For lIndex = 0 To numArgs - 1
lCodeToExecute = lCodeToExecute & "pArgs(" & lIndex & "), "
lIndex = lIndex + 1
Next
Dim lCutOff As Integer: lCutOff = 2
If lIndex = 0 Then lCutOff = 1
lCodeToExecute = left(lCodeToExecute, Len(lCodeToExecute) - lCutOff)
If lCutOff = 2 Then lCodeToExecute = lCodeToExecute & ")"
lCodeToExecute = lCodeToExecute & vbCrLf & " " & lProcNameToExecute & "= False" & vbCrLf & " Exit Function"
lCodeToExecute = lCodeToExecute & vbCrLf & lGoToLabel & ":" & vbCrLf
lCodeToExecute = lCodeToExecute & " " & lProcNameToExecute & "= True"
lCodeToExecute = lCodeToExecute & vbCrLf & "End Function"
mCreateCodeToExecute = lCodeToExecute
End Function
References
How to run a string as a command in VBA

Missing Leading Zeros in SQL Export to Excel Loop

New VB programmer here. I am exporting a SQL table to an Excel file using the following method below. However, when I create the file in excel, my leading zeros for my primary key are missing due to being converted to numbers instead of text. This is due to the information coming from the datatable to excel. I am wondering what I can do to keep my leading zeros.
FYI - my primary key is 6 digits with only a few that are missing a single 0 in the beginning of them. There are many other columns and rows that get put into the excel file after the first column which all work perfectly. It is only the first column primary keys which i need to change the format somehow.
Also, I am using this excel file to then upload into SQL and the missing 0 on some of the primary keys maks my program create a new record.
I was thinking the main change could take place here but I cannot figure out how to do so:
'Export the Columns to excel file
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In datatableMain.Rows
rowIndex = rowIndex + 1
colIndex = 1
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
Full Code Below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim dataAdapter As New SqlClient.SqlDataAdapter()
Dim dataSet As New DataSet
Dim command As New SqlClient.SqlCommand
Dim datatableMain As New System.Data.DataTable()
Dim connection As New SqlClient.SqlConnection
connection.ConnectionString = "Server=myserver;Database=mydatabase;User Id=xxxx;Password=xxxxx"
command.Connection = connection
command.CommandType = CommandType.Text
'You can use any command select
command.CommandText = "Select * from MYTABLE"
dataAdapter.SelectCommand = command
Dim f As FolderBrowserDialog = New FolderBrowserDialog
Try
If f.ShowDialog() = DialogResult.OK Then
'This section help you if your language is not English.
System.Threading.Thread.CurrentThread.CurrentCulture = _
System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add(Type.Missing)
oSheet = oBook.Worksheets(1)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
'Fill data to datatable
connection.Open()
dataAdapter.Fill(datatableMain)
connection.Close()
'Export the Columns to excel file
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In datatableMain.Rows
rowIndex = rowIndex + 1
colIndex = 1
For Each dc In datatableMain.Columns
colIndex = colIndex + 1
oSheet.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
'Set final path
Dim fileName As String = "\" + fname.Text + ".xlsx"
Dim finalPath = f.SelectedPath + fileName
txtPath.Text = finalPath
oSheet.Columns.AutoFit()
'Save file in final path
oBook.SaveAs(finalPath, Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
'Release the objects
ReleaseObject(oSheet)
oBook.Close(False, Type.Missing, Type.Missing)
ReleaseObject(oBook)
oExcel.Quit()
ReleaseObject(oExcel)
'Some time Office application does not quit after automation:
'so i am calling GC.Collect method.
GC.Collect()
MessageBox.Show("Exported!")
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK)
End Try
End If
End Sub
Private Sub ReleaseObject(ByVal o As Object)
Try
While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
End While
Catch
Finally
o = Nothing
End Try
End Sub
I actually just had a similar problem about 10 minutes ago! I needed to get a 30-something digit from one book to another and it was overflowing everything. Try setting the formatting of the column before writing to the cells. My code was Worksheets(i).Range("D:D").NumberFormat = "#" This will tell Excel to interperate the data "as is" instead of trying to guess what you want.
I found this question looking to fix this same issue in a generic function I have, that's used by a couple programs I've created. Due to that variety of data sources I couldn't hard code which columns to set the NumberFormat on. In order to get around it I leveraged the loop I have to output column headers. My code is below for those needing a little more of a dynamic solution. Note, there are a couple references to 'EL' that's an instance of a custom error logging object in the same solution, that can just be ignored/modified:
''' <summary>
''' Function to take a data table and output its contents to an Excel spreadsheet. Returns a string with any errors (Nothing if successful)
''' </summary>
''' <param name="D">The datatable to be output</param>
''' <param name="epath">The full file path to log errors to</param>
''' <param name="SAName">The full file path to save the created Excel workbook to</param>
''' <param name="Parent">The function calling for data to be output</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function ResOut(ByVal D As DataTable, ByVal epath As String, ByVal SAName As String, ByVal Parent As String) As String
'
Dim res As String = ""
Dim E As New Microsoft.Office.Interop.Excel.Application
Dim wb As Microsoft.Office.Interop.Excel.Workbook = Nothing
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = Nothing
Dim x As Long = 0
Dim f As Long = 1
Dim Rng As Microsoft.Office.Interop.Excel.Range = Nothing
Dim q As String
Dim Str_Columns As New List(Of String) 'Holds the list of column letters that need forced to Text format in order to retain leading zeroes in the data
'that will be placed there
'Check that the passed in table has data
If D.Rows.Count = 0 Then
res = "No data was returned by " & Parent
End If
If res = "" Then
'Create a workbook for the data and capture the workbook and sheet for ease of reference
Try
wb = E.Workbooks.Add
ws = wb.Worksheets(1)
'Define the range
q = ColNumToStr(D.Columns.Count, epath)
Rng = ws.Range("A2:" & q & D.Rows.Count + 1)
Catch ex As Exception
res = "Encountered an error while creating the new workbook to export the results to. No data can be returned."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
'Fill in headers
If res = "" Then
Try
For Each c As DataColumn In D.Columns
ws.Range("A1").Offset(0, x).Value = c.ColumnName
x = x + 1
Next
Catch ex As Exception
res = "Encountered an error while filling in the column headers. This will prevent any data from being returned."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
'Setup the step & frequency for the Step Progress bar
'Dim t() As Long = s.StatSetup(QR.Rows.Count, 58, "Query Runner\ResOut\" & QName, Replace(My.Settings.EPath, "<user>", Environment.UserName) & DStamp() & " Query Scheduler Log.txt")
'f = t(0)
'SProg.Step = t(1)
'Create the array
Dim OArr(D.Rows.Count, x) As Object
'Convert the datatable to a 2D array
If res = "" Then
Try
'Fill it
x = 0
For r As Long = 0 To D.Rows.Count - 1 Step 1
Dim dr As DataRow = D.Rows(r)
For c As Integer = 0 To D.Columns.Count - 1 Step 1
OArr(r, c) = dr.Item(c).ToString
'Check if this item is a # with leading zeroes (making sure we haven't already added the column to the list of such columns)
If Not (Str_Columns.Contains(ColNumToStr(c + 1, epath))) And Strings.Left(dr.Item(c), 1) = "0" Then
Str_Columns.Add(ColNumToStr(c + 1, epath))
End If 'else the column is in the list already or the item does not dictate it's inclusion
Next
x = x + 1
Next
Catch ex As Exception
res = "Encountered an error while outputing the " & x + 1 & "-th record of " & D.Rows.Count & ". No data will be output."
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
'output the array to the target range
If res = "" Then
'First force Text format where needed to retain leading zeroes
Try
For Each c As String In Str_Columns
q = c
ws.Range(c & ":" & c).NumberFormat = "#"
Next
Catch ex As Exception
res = "Encountered an error while changing column " & q & " to TEXT in order to retain leading zeroes in the " & ws.Range(q & 1).Value & "data."
E.Visible = True
wb.Activate()
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message & Chr(10) & Chr(10) & "Inner Exception: " & ex.InnerException.Message _
, epath)
End Try
Try
Rng.Value = OArr
'Save the workbook
wb.SaveAs(SAName)
wb.Close(SaveChanges:=False)
Catch ex As Exception
res = "Encountered an error during the export of the results. Some data may have been exported. Review the contents of the Excel workbook that will " _
& "be visible following this message for more details."
E.Visible = True
wb.Activate()
EL.AddErr(res & " ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
Else
'Close the workbook without saving
wb.Close(SaveChanges:=False)
End If
'Cleanup the application
Try
E.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(E)
E = Nothing
wb = Nothing
ws = Nothing
Rng = Nothing
OArr = Nothing
f = Nothing
x = Nothing
Catch ex As Exception
EL.AddErr("Encountered an error while cleaning up the resources used in JMLib\ResOut. ResOut was called by " & Parent & ". Error Details: " & ex.Message, epath)
End Try
End If
Return res
End Function

How to write the contents of the Immediate Window to a text file

I am very new to VBA. I searched a lot on the <header>, but I still don't get it.
This is my sample code:
Sub test()
a = 10
b = 2
c = 10 / b
Debug.Print c
On Error GoTo x
x:
If Err > 1 Then
Debug.Print "The most recent error number is " & Err & _
". Its message text is: " & Error(Err)
End If
End Sub
How do I write the output of immediate window to a text file or if any error to errorlog.txt file?
I tried a little like this:
sub test()
dim gofs:set gofs=createobject("scripting.filesystemobject")
dim tsout:set tsout=gofs.createtextfile(output)
You can add some error handling based on this article.
Option Explicit
Sub Main()
CreateFile ("C:\Users\" & Environ$("username") & "\Desktop\NewFile.txt")
Dim a&, b&, c&
a = 10
b = 2
c = 10 / b
ToFile c
On Error GoTo x
x:
If Err > 1 Then
ToFile "The most recent error number is " & Err & ". Its message text is: " & Error(Err)
End If
End Sub
Private Sub CreateFile(path As String)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile(path)
oFile.WriteLine Now & "file created by " & Environ$("username")
oFile.Close
End Sub
Private Sub ToFile(str As Variant)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim ofs As Object
If Len(Dir("C:\Users\" & Environ$("username") & "\Desktop\NewFile.txt")) > 0 Then
Set ofs = fso.OpenTextFile("C:\Users\" & Environ$("username") & "\Desktop\NewFile.txt", 8, True)
End If
ofs.WriteLine str
ofs.Close
End Sub
for an errorlog.txt, try this:
x:
If Err > 1 Then
Open "C:\temp\errorlog.txt" For Append As #1
Print #1, Date & " " & Time() & " - Error " & Err & ": " & _
Error(Err)
Close #1
End If

Automatically generating handling of issues

This is more an observation than a real question: MS-Access (and VBA in general) is desperately missing a tool where error handling code can be generated automatically, and where the line number can be displayed when an error occurs. Did you find a solution? What is it? I just realized how many hundreds of hours I spared since I found the right answer to this basic problem a few years ago, and I'd like to see what are your ideas and solutions on this very important issue.
What about using "Erl", it will display the last label before the error (e.g., 10, 20, or 30)?
Private Sub mySUB()
On Error GoTo Err_mySUB
10:
Dim stDocName As String
Dim stLinkCriteria As String
20:
stDocName = "MyDoc"
30:
DoCmd.openform stDocName, acFormDS, , stLinkCriteria
Exit_mySUB:
Exit Sub
Err_mySUB:
MsgBox Err.Number & ": " & Err.Description & " (" & Erl & ")"
Resume Exit_mySUB
End Sub
My solution is the following:
install MZ-Tools, a very interesting add-on for VBA. No they did not pay me to write this. Version 3 was free, but since version 8.0, the add-in is commercially sold.
program a standard error handler code such as this one (see MZ-Tools menu/Options/Error handler):
On Error GoTo {PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
On Error GoTo 0
Exit {PROCEDURE_TYPE}
{PROCEDURE_NAME}_Error:
debug.print "#" & Err.Number, Err.description, "l#" & erl, "{PROCEDURE_NAME}", "{MODULE_NAME}"
This standard error code can be then automatically added to all of your procs and function by clicking on the corresponding button in the MZ-Tools menu. You'll notice that we refer here to a hidden and undocumented function in the VBA standard library, 'Erl', which stands for 'error line'. You got it! If you ask MZ-Tools to automatically number your lines of code, 'Erl' will then give you the number of the line where the error occured. You will have a complete description of the error in your immediate window, such as:
#91, Object variable or With block variable not set, l# 30, addNewField, Utilities
Of course, once you realize the interest of the system, you can think of a more sophisticated error handler, that will not only display the data in the debug window but will also:
display it as a message on the screen
Automatically insert a line in an error log file with the description of the error or
if you are working with Access or if you are connected to a database, automatically add a record to a Tbl_Error table!
meaning that each error generated at the user level can be stored either in a file or a table, somewhere on the machine or the network. Are we talking about building an automated error reporting system working with VBA?
Well there are a couple of tools that will do what you ask MZ Tools and FMS Inc come to mind.
Basically they involve adding an:
On Error GoTo ErrorHandler
to the top of each proc
and at the end they put an:
ErrorHandler:
Call MyErrorhandler Err.Number, Err.Description, Err.LineNumber
label with usually a call to a global error handler where you can display and log custom error messages
You can always roll your own tool like Chip Pearson did. VBA can actually access it's own IDE via the Microsoft Visual Basic for Applications Extensibility 5.3 Library. I've written a few class modules that make it easier to work with myself. They can be found on Code Review SE.
I use it to insert On Error GoTo ErrHandler statements and the appropriate labels and constants related to my error handling schema. I also use it to sync up the constants with the actual procedure names (if the function names should happen to change).
There is no need to buy tools DJ mentioned. Here is my code for free:
Public Sub InsertErrHandling(modName As String)
Dim Component As Object
Dim Name As String
Dim Kind As Long
Dim FirstLine As Long
Dim ProcLinesCount As Long
Dim Declaration As String
Dim ProcedureType As String
Dim Index As Long, i As Long
Dim LastLine As Long
Dim StartLines As Collection, LastLines As Collection, ProcNames As Collection, ProcedureTypes As Collection
Dim gotoErr As Boolean
Kind = 0
Set StartLines = New Collection
Set LastLines = New Collection
Set ProcNames = New Collection
Set ProcedureTypes = New Collection
Set Component = Application.VBE.ActiveVBProject.VBComponents(modName)
With Component.CodeModule
' Remove empty lines on the end of the code
For i = .CountOfLines To 1 Step -1
If Component.CodeModule.Lines(i, 1) = "" Then
Component.CodeModule.DeleteLines i, 1
Else
Exit For
End If
Next i
Index = .CountOfDeclarationLines + 1
Do While Index < .CountOfLines
gotoErr = False
Name = .ProcOfLine(Index, Kind)
FirstLine = .ProcBodyLine(Name, Kind)
ProcLinesCount = .ProcCountLines(Name, Kind)
Declaration = Trim(.Lines(FirstLine, 1))
LastLine = FirstLine + ProcLinesCount - 2
If InStr(1, Declaration, "Function ", vbBinaryCompare) > 0 Then
ProcedureType = "Function"
Else
ProcedureType = "Sub"
End If
Debug.Print Component.Name & "." & Name, "First: " & FirstLine, "Lines:" & ProcLinesCount, "Last: " & LastLine, Declaration
Debug.Print "Declaration: " & Component.CodeModule.Lines(FirstLine, 1), FirstLine
Debug.Print "Closing Proc: " & Component.CodeModule.Lines(LastLine, 1), LastLine
' do not insert error handling if there is one already:
For i = FirstLine To LastLine Step 1
If Component.CodeModule.Lines(i, 1) Like "*On Error*" Then
gotoErr = True
Exit For
End If
Next i
If Not gotoErr Then
StartLines.Add FirstLine
LastLines.Add LastLine
ProcNames.Add Name
ProcedureTypes.Add ProcedureType
End If
Index = FirstLine + ProcLinesCount + 1
Loop
For i = LastLines.Count To 1 Step -1
If Not (Component.CodeModule.Lines(StartLines.Item(i) + 1, 1) Like "*On Error GoTo *") Then
Component.CodeModule.InsertLines LastLines.Item(i), "ExitProc_:"
Component.CodeModule.InsertLines LastLines.Item(i) + 1, " Exit " & ProcedureTypes.Item(i)
Component.CodeModule.InsertLines LastLines.Item(i) + 2, "ErrHandler_:"
Component.CodeModule.InsertLines LastLines.Item(i) + 3, " Call LogError(Err, Me.Name, """ & ProcNames.Item(i) & """)"
Component.CodeModule.InsertLines LastLines.Item(i) + 4, " Resume ExitProc_"
Component.CodeModule.InsertLines LastLines.Item(i) + 5, " Resume ' use for debugging"
Component.CodeModule.InsertLines StartLines.Item(i) + 1, " On Error GoTo ErrHandler_"
End If
Next i
End With
End Sub
Put it in a module and call it from Immediate Window every time you add new function or sub to a form or module like this (Form1 is name of your form):
MyModule.InsertErrHandling "Form_Form1"
It will alter your ode in Form1 from this:
Private Function CloseIt()
DoCmd.Close acForm, Me.Name
End Function
to this:
Private Function CloseIt()
On Error GoTo ErrHandler_
DoCmd.Close acForm, Me.Name
ExitProc_:
Exit Function
ErrHandler_:
Call LogError(Err, Me.Name, "CloseIt")
Resume ExitProc_
Resume ' use for debugging
End Function
Create now in a module a Sub which will display the error dialog and where you can add inserting the error to a text file or database:
Public Sub LogError(ByVal objError As ErrObject, moduleName As String, Optional procName As String = "")
On Error GoTo ErrHandler_
Dim sql As String
MsgBox "Error " & Err.Number & " Module " & moduleName & Switch(procName <> "", " in " & procName) & vbCrLf & " (" & Err.Description & ") ", vbCritical
Exit_:
Exit Sub
ErrHandler_:
MsgBox "Error in LogError procedure " & Err.Number & ", " & Err.Description
Resume Exit_
Resume ' use for debugging
End Sub
This code does not enter error handling if there is already "On Error" statement in a proc.
Love it Vlado!
I realize this is an old post, but I grabbed it and gave it a try, but I ran into a number of issues with it, which I managed to fix. Here's the code with fixes:
First of course, be sure to add the "Microsoft Visual Basic for Applications Extensibility 5.3" library to your project, and add these subroutines / modules to your project as well.
First, the module with the main code was named "modVBAChecks", and contained the following two subroutines:
To go through all modules (behind forms, sheets, the workbook, and classes as well, though not ActiveX Designers):
Sub AddErrorHandlingToAllProcs()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim lCtr As Long
StartNewWorksheetLog
Set VBProj = Workbooks("LabViewAnalysisTools.xla").VBProject
For Each VBComp In VBProj.VBComponents
If VBComp.Type <> vbext_ct_ActiveXDesigner Then
If VBComp.Name <> "modVBAChecks" And VBComp.Name <> "modLogToWorksheet" Then
AddToWksLog "============ Looking at Module """ & VBComp.Name & """"
'InsertErrHandling VBComp.Name
AddToWksLog
AddToWksLog
End If
End If
Next
MsgBox "Done!", vbSystemModal
End Sub
Then the modified version of your code (including a suggested change by
RafaƂ B.):
Public Sub InsertErrHandling(modsProcName As String)
' Modified from code submitted to StackOverflow by user Vlado, originally found
' here: https://stackoverflow.com/questions/357822/automatically-generating-handling-of-issues
Dim vbcmA As VBIDE.CodeModule
Dim ProcKind As VBIDE.vbext_ProcKind
Dim LineProcKind As VBIDE.vbext_ProcKind
Dim sProcName As String
Dim sLineProcName As String
Dim lFirstLine As Long
Dim lProcLinesCount As Long
Dim lLastLine As Long
Dim sDeclaration As String
Dim sProcType As String
Dim lLine As Long, lLine2 As Long
Dim sLine As String
Dim lcStartLines As Collection, lcLastlines As Collection, scProcsProcNames As Collection, scProcTypes As Collection
Dim bAddHandler As Boolean
Dim lLinesAbove As Long
Set lcStartLines = New Collection
Set lcLastlines = New Collection
Set scProcsProcNames = New Collection
Set scProcTypes = New Collection
Set vbcmA = Application.VBE.ActiveVBProject.VBComponents(modsProcName).CodeModule
' Remove empty lines on the end of the module. Cleanup, not error handling.
lLine = vbcmA.CountOfLines
If lLine = 0 Then Exit Sub ' Nothing to do!
Do
If Trim(vbcmA.Lines(lLine, 1)) <> "" Then Exit Do
vbcmA.DeleteLines lLine, 1
lLine = lLine - 1
Loop
lLine = vbcmA.CountOfDeclarationLines + 1
Do While lLine < vbcmA.CountOfLines
bAddHandler = False
' NOTE: ProcKind is RETRUNED from ProcOfLine!
sProcName = vbcmA.ProcOfLine(lLine, ProcKind)
' Fortunately ProcBodyLine ALWAYS returns the first line of the procedure declaration!
lFirstLine = vbcmA.ProcBodyLine(sProcName, ProcKind)
sDeclaration = Trim(vbcmA.Lines(lFirstLine, 1))
Select Case ProcKind
Case VBIDE.vbext_ProcKind.vbext_pk_Proc
If sDeclaration Like "*Function *" Then
sProcType = "Function"
ElseIf sDeclaration Like "*Sub *" Then
sProcType = "Sub"
End If
Case VBIDE.vbext_ProcKind.vbext_pk_Get, VBIDE.vbext_ProcKind.vbext_pk_Let, VBIDE.vbext_ProcKind.vbext_pk_Set
sProcType = "Property"
End Select
' The "lProcLinesCount" function will sometimes return ROWS ABOVE
' the procedure, possibly up until the prior procedure,
' and often rows BELOW the procedure as well!!!
lProcLinesCount = vbcmA.ProcCountLines(sProcName, ProcKind)
lLinesAbove = 0
lLine2 = lFirstLine - 1
If lLine2 > 0 Then
Do
sLineProcName = vbcmA.ProcOfLine(lLine2, LineProcKind)
If Not (sLineProcName = sProcName And LineProcKind = ProcKind) Then Exit Do
lLinesAbove = lLinesAbove + 1
lLine2 = lLine2 - 1
If lLine2 = 0 Then Exit Do
Loop
End If
lLastLine = lFirstLine + lProcLinesCount - lLinesAbove - 1
' Now need to trim off any follower lines!
Do
sLine = Trim(vbcmA.Lines(lLastLine, 1))
If sLine = "End " & sProcType Or sLine Like "End " & sProcType & " '*" Then Exit Do
lLastLine = lLastLine - 1
Loop
AddToWksLog modsProcName & "." & sProcName, "First: " & lFirstLine, "Lines:" & lProcLinesCount, "Last: " & lLastLine
AddToWksLog "sDeclaration: " & vbcmA.Lines(lFirstLine, 1), lFirstLine
AddToWksLog "Closing Proc: " & vbcmA.Lines(lLastLine, 1), lLastLine
If lLastLine - lFirstLine < 8 Then
AddToWksLog " --------------- Too Short to bother!"
Else
bAddHandler = True
' do not insert error handling if there is one already:
For lLine2 = lFirstLine To lLastLine Step 1
If vbcmA.Lines(lLine2, 1) Like "*On Error GoTo *" And Not vbcmA.Lines(lLine2, 1) Like "*On Error GoTo 0" Then
bAddHandler = False
Exit For
End If
Next lLine2
If bAddHandler Then
lcStartLines.Add lFirstLine
lcLastlines.Add lLastLine
scProcsProcNames.Add sProcName
scProcTypes.Add sProcType
End If
End If
AddToWksLog
lLine = lFirstLine + lProcLinesCount + 1
Loop
For lLine = lcLastlines.Count To 1 Step -1
vbcmA.InsertLines lcLastlines.Item(lLine), "ExitProc:"
vbcmA.InsertLines lcLastlines.Item(lLine) + 1, " Exit " & scProcTypes.Item(lLine)
vbcmA.InsertLines lcLastlines.Item(lLine) + 2, "ErrHandler:"
vbcmA.InsertLines lcLastlines.Item(lLine) + 3, " ShowErrorMsg Err, """ & scProcsProcNames.Item(lLine) & """, """ & modsProcName & """"
vbcmA.InsertLines lcLastlines.Item(lLine) + 4, " Resume ExitProc"
' Now replace any "On Error Goto 0" lines with "IF ErrorTrapping Then On Error Goto ErrHandler"
For lLine2 = lcStartLines(lLine) To lcLastlines(lLine)
sLine = vbcmA.Lines(lLine2, 1)
If sLine Like "On Error GoTo 0" Then
vbcmA.ReplaceLine lLine2, Replace(sLine, "On Error Goto 0", "IF ErrorTrapping Then On Error Goto ErrHandler")
End If
Next
lLine2 = lcStartLines.Item(lLine)
Do
sLine = vbcmA.Lines(lLine2, 1)
If Not sLine Like "* _" Then Exit Do
lLine2 = lLine2 + 1
Loop
vbcmA.InsertLines lLine2 + 1, " If ErrorTrapping Then On Error GoTo ErrHandler"
Next lLine
End Sub
And rather than pushing things to the Immediate window I used subroutines in a module I named "modLogToWorksheet", the full module being here:
Option Explicit
Private wksLog As Worksheet
Private lRow As Long
Public Sub StartNewWorksheetLog()
Dim bNewSheet As Boolean
bNewSheet = True
If ActiveSheet.Type = xlWorksheet Then
Set wksLog = ActiveSheet
bNewSheet = Not (wksLog.UsedRange.Cells.Count = 1 And wksLog.Range("A1").Formula = "")
End If
If bNewSheet Then Set wksLog = ActiveWorkbook.Worksheets.Add
lRow = 1
End Sub
Public Sub AddToWksLog(ParamArray sMsg() As Variant)
Dim lCol As Long
If wksLog Is Nothing Or lRow = 0 Then StartNewWorksheetLog
If Not (IsNull(sMsg)) Then
For lCol = 0 To UBound(sMsg)
If sMsg(lCol) <> "" Then wksLog.Cells(lRow, lCol + 1).Value = "'" & sMsg(lCol)
Next
End If
lRow = lRow + 1
End Sub
And finally, here's my Error Dialog generator:
Public Sub ShowErrorMsg(errThis As ErrObject, strSubName As String, strModName As String _
, Optional vbMBStyle As VbMsgBoxStyle = vbCritical, Optional sTitle As String = APP_TITLE)
If errThis.Number <> 0 Then
MsgBox "An Error Has Occurred in the Add-in. Please inform " & ADMINS & " of this problem." _
& vbCrLf & vbCrLf _
& "Error #: " & errThis.Number & vbCrLf _
& "Description: " & " " & errThis.Description & vbCrLf _
& "Subroutine: " & " " & strSubName & vbCrLf _
& "Module: " & " " & strModName & vbCrLf _
& "Source: " & " " & errThis.Source & vbCrLf & vbCrLf _
& "Click OK to continue.", vbMBStyle Or vbSystemModal, sTitle
End If
End Sub
Hope future users find it useful!