C# Snippets
Bookmark_Exists
public bool Bookmark_Exists(ref Word.Document objDocument, string sBookmarkName, bool bInformUser = false)
{
try
{
Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod().Name + " start");
if (My.Settings.ERROR_OCCURRED == true)
return;
return objDocument.Bookmarks.Exists(sBookmarkName);
}
catch (Exception ex)
{
if ((bInformUser == true))
modMessages.Bookmark_DoesNotExist(sBookmarkName);
}
}
Public Function Bookmark_Exists(ByRef objDocument As Word.Document, _
ByVal sBookmarkName As String, _
Optional ByVal bInformUser As Boolean = False) As Boolean
Try
Call Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod.Name & " start")
If My.Settings.ERROR_OCCURRED = True Then Exit Function
Return objDocument.Bookmarks.Exists(sBookmarkName)
Catch ex As System.Exception
If (bInformUser = True) Then
Call modMessages.Bookmark_DoesNotExist(sBookmarkName)
End If
End Try
End Function
Field_CodeTextExists
public bool Field_CodeTextExists(ref Word.Document objDocument, int ifieldcount, bool bInformUser = true)
{
Word.Field oField;
try
{
Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod().Name + " start");
if (My.Settings.ERROR_OCCURRED == true)
return;
oField = objDocument.Fields(ifieldcount);
if (!(oField.Code.Text == null))
return true;
else
{
if ((bInformUser == true))
modMessages.Field_InvalidCodeText(oField);
return false;
}
}
catch (Exception ex)
{
modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod(), null/* TODO Change to default(_) if this is not a reference type */, ex);
}
}
Public Function Field_CodeTextExists(ByRef objDocument As Word.Document, _
ByVal ifieldcount As Integer, _
Optional ByVal bInformUser As Boolean = True) As Boolean
Dim oField As Word.Field
Try
Call Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod.Name & " start")
If My.Settings.ERROR_OCCURRED = True Then Exit Function
oField = objDocument.Fields(ifieldcount)
If Not (oField.Code.Text Is Nothing) Then
Return True
Else
If (bInformUser = True) Then
Call modMessages.Field_InvalidCodeText(oField)
End If
Return False
End If
Catch ex As System.Exception
Call modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod, Nothing, ex)
End Try
End Function
Fields_DocumentContainsAny
public static bool DocumentContainsAny(string sDocumentName = "")
{
Word.Document objdocument;
try
{
if (clsError.ErrorFlag() == true)
return;
if (sDocumentName != "")
objdocument = gApplicationWord.Documents(sDocumentName);
else
objdocument = gApplicationWord.ActiveDocument;
if (objdocument.Fields.Count > 0)
DocumentContainsAny = true;
else
DocumentContainsAny = false;
}
catch (Runtime.InteropServices.COMException objCOMException)
{
mobjCOMException = objCOMException;
}
catch (Exception objException)
{
mobjException = objException;
}
finally
{
if (gbDEBUG_WORD == true | ((!mobjCOMException == null) | (!mobjException == null)))
clsError.Handle("DocumentContainsAny", msCLASSNAME, "determine if the document contains any fields.", mobjCOMException, mobjException);
}
}
Public Shared Function DocumentContainsAny(Optional ByVal sDocumentName As String = "") _
As Boolean
Dim objdocument As Word.Document
Try
If clsError.ErrorFlag() = True Then Exit Function
If sDocumentName <> "" Then
objdocument = gApplicationWord.Documents(sDocumentName)
Else
objdocument = gApplicationWord.ActiveDocument
End If
If objdocument.Fields.Count > 0 Then
DocumentContainsAny = True
Else
DocumentContainsAny = False
End If
Catch objCOMException As System.Runtime.InteropServices.COMException
mobjCOMException = objCOMException
Catch objException As Exception
mobjException = objException
Finally
If gbDEBUG_WORD = True Or _
((Not mobjCOMException Is Nothing) Or (Not mobjException Is Nothing)) Then
Call clsError.Handle("DocumentContainsAny", msCLASSNAME, _
"determine if the document contains any fields.", _
mobjCOMException, mobjException)
End If
End Try
End Function
Fields_DocumentContainsAnyType
public static bool DocumentContainsAnyType(Word.WdFieldType objFieldType, string sDocumentName = "")
{
Word.Document objdocument;
int ifieldcount;
try
{
if (clsError.ErrorFlag() == true)
return;
if (sDocumentName != "")
objdocument = gApplicationWord.Documents(sDocumentName);
else
objdocument = gApplicationWord.ActiveDocument;
DocumentContainsAnyType = false;
if (objdocument.Fields.Count > 0)
{
for (ifieldcount = 1; ifieldcount <= objdocument.Fields.Count; ifieldcount++)
{
if (objdocument.Fields(ifieldcount).Type == objFieldType)
DocumentContainsAnyType = true;
}
}
}
catch (Runtime.InteropServices.COMException objCOMException)
{
mobjCOMException = objCOMException;
}
catch (Exception objException)
{
mobjException = objException;
}
finally
{
if (gbDEBUG_WORD == true | ((!mobjCOMException == null) | (!mobjException == null)))
clsError.Handle("DocumentContainsAnyType", msCLASSNAME, " .", mobjCOMException, mobjException);
}
}
Public Shared Function DocumentContainsAnyType(ByVal objFieldType As Word.WdFieldType, _
Optional ByVal sDocumentName As String = "") _
As Boolean
Dim objdocument As Word.Document
Dim ifieldcount As Integer
Try
If clsError.ErrorFlag() = True Then Exit Function
If sDocumentName <> "" Then
objdocument = gApplicationWord.Documents(sDocumentName)
Else
objdocument = gApplicationWord.ActiveDocument
End If
DocumentContainsAnyType = False
If objdocument.Fields.Count > 0 Then
For ifieldcount = 1 To objdocument.Fields.Count
If objdocument.Fields(ifieldcount).Type = objFieldType Then
DocumentContainsAnyType = True
End If
Next ifieldcount
End If
Catch objCOMException As System.Runtime.InteropServices.COMException
mobjCOMException = objCOMException
Catch objException As Exception
mobjException = objException
Finally
If gbDEBUG_WORD = True Or _
((Not mobjCOMException Is Nothing) Or (Not mobjException Is Nothing)) Then
Call clsError.Handle("DocumentContainsAnyType", msCLASSNAME, _
" .", _
mobjCOMException, mobjException)
End If
End Try
End Function
Fields_UnlinkAll
public void Fields_UnlinkAll(ref Word.Document objDocument)
{
Word.Field objField;
try
{
foreach (var objField in objDocument.Fields)
{
if (objField.Type == Word.WdFieldType.wdFieldDDEAuto)
objField.Unlink();
}
}
catch (Exception ex)
{
modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod(), null/* TODO Change to default(_) if this is not a reference type */, ex);
}
}
Public Sub Fields_UnlinkAll(ByRef objDocument As Word.Document)
Dim objField As Word.Field
Try
For Each objField In objDocument.Fields
If objField.Type = Word.WdFieldType.wdFieldDDEAuto Then
objField.Unlink()
End If
'objField.LinkFormat.BreakLink
Next objField
Catch ex As Exception
Call modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod, Nothing, ex)
End Try
End Sub
Fields_UpdateAll
Updates all the fields in the active document, including all sections, headers and footers.public void Fields_Update(ref Word.Document objDocument)Updates all the fields in the active document, including all sections, headers and footers.
{
// Updates Field Numbers for Charts and Tables
int i;
string strField;
try
{
Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod().Name + " start");
if (My.Settings.ERROR_OCCURRED == true)
return;
if (objDocument.Fields.Count == 0)
return;
for (i = objDocument.Fields.Count; i >= 1; i += -1)
{
strField = objDocument.Fields(i).Code.Text;
if (Microsoft.VisualBasic.InStr(1, strField, @"SEQ Figure \* ARABIC") > 0 | Microsoft.VisualBasic.InStr(1, strField, "REF _Ref") > 0)
objDocument.Fields(i).Update();
}
}
catch (Exception ex)
{
modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod(), null/* TODO Change to default(_) if this is not a reference type */, ex);
}
}
Public Sub Fields_Update(ByRef objDocument As Word.Document)
'Updates Field Numbers for Charts and Tables
Dim i As Integer
Dim strField As String
Try
Call Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod.Name & " start")
If My.Settings.ERROR_OCCURRED = True Then Exit Sub
If objDocument.Fields.Count = 0 Then
Exit Sub
End If
For i = objDocument.Fields.Count To 1 Step -1
strField = objDocument.Fields(i).Code.Text
If Microsoft.VisualBasic.InStr(1, strField, "SEQ Figure \* ARABIC") > 0 Or _
Microsoft.VisualBasic.InStr(1, strField, "REF _Ref") > 0 Then
objDocument.Fields(i).Update()
End If
Next i
Catch ex As System.Exception
Call modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod, Nothing, ex)
End Try
End Sub
GoToTypeText
public static void GoToTypeText(string sBookmarkName, string sText)
{
try
{
if (clsError.ErrorFlag() == true)
return;
clszLateBindingWord.SelectionGoToBookmark(sBookmarkName);
gApplicationWord.Selection.TypeText(Text: sText);
}
catch (Runtime.InteropServices.COMException objCOMException)
{
mobjCOMException = objCOMException;
}
catch (Exception objException)
{
mobjException = objException;
}
finally
{
if (gbDEBUG_WORD == true | ((!mobjCOMException == null) | (!mobjException == null)))
clsError.Handle("GoToTypeText", msCLASSNAME, "insert the text '" + sText + "' into the bookmark '" + sBookmarkName + "'.", mobjCOMException, mobjException);
}
}
Public Shared Sub GoToTypeText(ByVal sBookmarkName As String, _
ByVal sText As String)
Try
If clsError.ErrorFlag() = True Then Exit Sub
Call clszLateBindingWord.SelectionGoToBookmark(sBookmarkName)
gApplicationWord.Selection.TypeText(Text:=sText)
Catch objCOMException As System.Runtime.InteropServices.COMException
mobjCOMException = objCOMException
Catch objException As Exception
mobjException = objException
Finally
If gbDEBUG_WORD = True Or _
((Not mobjCOMException Is Nothing) Or (Not mobjException Is Nothing)) Then
Call clsError.Handle("GoToTypeText", msCLASSNAME, _
"insert the text '" & sText & "' into the bookmark '" & sBookmarkName & "'.", _
mobjCOMException, mobjException)
End If
End Try
End Sub
HeaderUpdate
public static void HeaderUpdate(int iSectionNo, Word.WdHeaderFooterIndex objHeaderFooterType)
{
try
{
if (clsError.ErrorFlag() == true)
return;
Word.HeaderFooter objHeader;
Word.Field objField;
if (gApplicationWord.ActiveDocument.Sections.Count < iSectionNo)
{
clszMessagesWord.SectionDoesNotExistInformation(iSectionNo);
return;
}
objHeader = gApplicationWord.ActiveDocument.Sections(iSectionNo).Headers(objHeaderFooterType);
foreach (var objField in objHeader.Range.Fields)
objField.Update();
}
catch (Runtime.InteropServices.COMException objCOMException)
{
mobjCOMException = objCOMException;
}
catch (Exception objException)
{
mobjException = objException;
}
finally
{
if (gbDEBUG_WORD == true | ((!mobjCOMException == null) | (!mobjException == null)))
clsError.Handle("HeaderUpdate", msCLASSNAME, " .", mobjCOMException, mobjException);
}
}
Public Shared Sub HeaderUpdate(ByVal iSectionNo As Integer, _
ByVal objHeaderFooterType As Word.WdHeaderFooterIndex)
Try
If clsError.ErrorFlag() = True Then Exit Sub
Dim objHeader As Word.HeaderFooter
Dim objField As Word.Field
If gApplicationWord.ActiveDocument.Sections.Count < iSectionNo Then
Call clszMessagesWord.SectionDoesNotExistInformation(iSectionNo)
Exit Sub
End If
objHeader = gApplicationWord.ActiveDocument.Sections(iSectionNo).Headers(objHeaderFooterType)
For Each objField In objHeader.Range.Fields
objField.Update()
Next objField
Catch objCOMException As System.Runtime.InteropServices.COMException
mobjCOMException = objCOMException
Catch objException As Exception
mobjException = objException
Finally
If gbDEBUG_WORD = True Or _
((Not mobjCOMException Is Nothing) Or (Not mobjException Is Nothing)) Then
Call clsError.Handle("HeaderUpdate", msCLASSNAME, _
" .", _
mobjCOMException, mobjException)
End If
End Try
End Sub
Message_Bookmark_DoesNotExist
public void Bookmark_DoesNotExist(string sBookmarkName)
{
string smessage = "";
smessage = "The bookmark '" + sBookmarkName + "' does not exist in this document.";
System.Windows.Forms.MessageBox.Show(smessage, My.Settings.APP_WINFORMS_TITLE, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
smessage = smessage + " (" + System.Reflection.MethodBase.GetCurrentMethod().Name + ")";
Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "));
}
Public Sub Bookmark_DoesNotExist(ByVal sBookmarkName As String)
Dim smessage As String = ""
smessage = "The bookmark '" & sBookmarkName & "' does not exist in this document."
System.Windows.Forms.MessageBox.Show(smessage, _
My.Settings.APP_WINFORMS_TITLE, _
System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Information)
smessage = smessage & " (" & System.Reflection.MethodBase.GetCurrentMethod.Name & ")"
Call Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "))
End Sub
Message_Field_InvalidCodeText
public void Field_InvalidCodeText(Word.Field objField)
{
string smessage = "";
smessage = "This document contains an invalid '" + objField.Type.ToString() + "' field.";
System.Windows.Forms.MessageBox.Show(smessage, My.Settings.APP_WINFORMS_TITLE + " - Invalid Field", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
smessage = smessage + " (" + System.Reflection.MethodBase.GetCurrentMethod().Name + ")";
Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "));
}
Public Sub Field_InvalidCodeText(ByVal objField As Word.Field)
Dim smessage As String = ""
smessage = "This document contains an invalid '" & objField.Type.ToString() & "' field."
System.Windows.Forms.MessageBox.Show(smessage, _
My.Settings.APP_WINFORMS_TITLE & " - Invalid Field", _
System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Information)
smessage = smessage & " (" & System.Reflection.MethodBase.GetCurrentMethod.Name & ")"
Call Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "))
End Sub
Message_Figures_AutoNumbersRemoved
public void Figures_AutoNumbersRemoved()
{
string smessage = "";
smessage = "Existing figure fields have been removed from this document.";
System.Windows.Forms.MessageBox.Show(smessage, My.Settings.APP_WINFORMS_TITLE, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
smessage = smessage + " (" + System.Reflection.MethodBase.GetCurrentMethod().Name + ")";
Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "));
}
Public Sub Figures_AutoNumbersRemoved()
Dim smessage As String = ""
smessage = "Existing figure fields have been removed from this document."
System.Windows.Forms.MessageBox.Show(smessage, _
My.Settings.APP_WINFORMS_TITLE, _
System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Information)
smessage = smessage & " (" & System.Reflection.MethodBase.GetCurrentMethod.Name & ")"
Call Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "))
End Sub
Message_Figures_HaveBeenUpdated
public void Figures_HaveBeenUpdated()
{
string smessage = "";
smessage = "All the Figure Numbers in this document have been updated.";
System.Windows.Forms.MessageBox.Show(smessage, My.Settings.APP_WINFORMS_TITLE, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
smessage = smessage + " (" + System.Reflection.MethodBase.GetCurrentMethod().Name + ")";
Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "));
}
Public Sub Figures_HaveBeenUpdated()
Dim smessage As String = ""
smessage = "All the Figure Numbers in this document have been updated."
System.Windows.Forms.MessageBox.Show(smessage, _
My.Settings.APP_WINFORMS_TITLE, _
System.Windows.Forms.MessageBoxButtons.OK, _
System.Windows.Forms.MessageBoxIcon.Information)
smessage = smessage & " (" & System.Reflection.MethodBase.GetCurrentMethod.Name & ")"
Call Tracer_Add2("MESSAGE", smessage.Replace(System.Environment.NewLine, " ").Replace(" ", " "))
End Sub
RemoveFigures
public void Fields_RemoveFigures(ref Word.Document objDocument)
{
int i;
string strField;
try
{
Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod().Name + " start");
if (My.Settings.ERROR_OCCURRED == true)
return;
if (objDocument.Fields.Count == 0)
return;
for (i = objDocument.Fields.Count; i >= 1; i += -1)
{
strField = objDocument.Fields(i).Code.Text;
if (Microsoft.VisualBasic.InStr(1, strField, @"SEQ Figure \* ARABIC") > 0 | Microsoft.VisualBasic.InStr(1, strField, "REF _Ref") > 0)
objDocument.Fields(i).Unlink();
}
}
catch (Exception ex)
{
modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod(), null/* TODO Change to default(_) if this is not a reference type */, ex);
}
}
Public Sub Fields_RemoveFigures(ByRef objDocument As Word.Document)
Dim i As Integer
Dim strField As String
Try
Call Tracer_Add2("SUBROUTINE", System.Reflection.MethodBase.GetCurrentMethod.Name & " start")
If My.Settings.ERROR_OCCURRED = True Then Exit Sub
If objDocument.Fields.Count = 0 Then
Exit Sub
End If
For i = objDocument.Fields.Count To 1 Step -1
strField = objDocument.Fields(i).Code.Text
If Microsoft.VisualBasic.InStr(1, strField, "SEQ Figure \* ARABIC") > 0 Or _
Microsoft.VisualBasic.InStr(1, strField, "REF _Ref") > 0 Then
objDocument.Fields(i).Unlink()
End If
Next i
Catch ex As System.Exception
Call modMessages.Exception(System.Reflection.MethodBase.GetCurrentMethod, Nothing, ex)
End Try
End Sub
SelectionGoToBookmark
public static void SelectionGoToBookmark(string sBookmarkName)
{
gApplicationWord.Selection.GoTo(What: Word.WdGoToItem.wdGoToBookmark, Name: sBookmarkName);
}
Public Shared Sub SelectionGoToBookmark(ByVal sBookmarkName As String)
gApplicationWord.Selection.GoTo(What:=Word.WdGoToItem.wdGoToBookmark, _
Name:=sBookmarkName)
End Sub
© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited Top