Showing posts with label Word VBA. Show all posts
Showing posts with label Word VBA. Show all posts

Saturday, January 25, 2014

How to Extract Wild Card Matches in Word Document using Word VBA / Export Find Matches to Text File using VBA

How to use Word VBA to Find Wild Card Matches in Multiple Word Documents and Extract them 


There are many situations where a particular format throughout the document that needs to be extracted. The answer would be 


1) Wild Card Search
2) Regular expressions

Lets consider wild card search for this post for a document that contains Reference Citations within square brackets [...]

The following snippet Loops through all documents in a folder, opens them and searches for content within Square Brackets 

It exports the matches to a Text File (Can store in Excel also)


Sub Extract_WildCard_Matches()

Dim sWildCard As String
Dim sDir
Dim oWD As Word.Document
Dim sPath As String


sWildCard = "\[[!\[\]]{1,}\]"

sPath = "C:\Documents\"
sDir = Dir$(sPath & "*.docx", vbNormal)

Do Until LenB(sDir) = 0

 Set oWD = Documents.Open(sPath & sDir)

    Open "C:\Match_Output.txt" For Append As #1
    
        Selection.HomeKey wdStory, wdMove
        
        Selection.Find.Execute FindText:=sWildCard, MatchWildcards:=True
        
        Do While Selection.Find.Found
            
            Print #1, ActiveDocument.Name & vbTab & Selection.Range.Text
            
            Selection.Range.Collapse wdCollapseEnd
            
            Selection.Find.Execute
        Loop
        
    Close #1

 oWD.Close False

 sDir = Dir$

Loop




End Sub

Sunday, May 06, 2012

UnInstall Word Addins using VBA


Here is a simple method to uninstall a Word Addin (.dot file) using Word VBA
Private Sub UnInstalled_AllWordAddins()
Dim oAddin As AddIn
On Error GoTo Err_Addin
For Each oAddin In AddIns
If oAddin.Installed Then
msg = oAddin.Name
oAddin.Installed = False
End If
Next oAddin
Finally:
If Not oAddin Is Nothing Then Set oAddin = Nothing
Err_Addin:
If Err < > 0 Then
Err.Clear
GoTo Finally
End If
End Sub

Installed Word Addin

Word Addin List after Macro Execution. Addin is uninstalled (not removed)

Friday, September 25, 2009

How to export Word Range as RTF using VBA

Save Selected Word Range as RTF using Word VBA

The following snippet saves the selected Range as RTF using VBA (Word 2007)

Sub Export_Selection_As_RTF()

Selection.Range.ExportFragment "C:\Users\comp\AppData\Local\Temp\Sample.rtf", wdFormatRTF

End Sub

See also:

Save RTF document as word

Visual Basic Common Dialog

Monday, April 27, 2009

How to Kill the Word Process using VBA

Developers who are working on Word VBA would have experienced the Word Crash problem more often.

Here is a crude way to kill the Word process.
Sub Kill_Word()

Dim sKillWord As String

sKillWord = "TASKKILL /F /IM Winword.exe"

Shell sKillWord, vbHide

End Sub


Process Window

Use this option if you are sure that the process is unused one

Sunday, January 04, 2009

How to Show Field Codes in Word Document – using VBA

Word VBA – Show Field Codes

Here is a simple way to show the field codes in Word

Sub Show_Field_Codes()

Application.ActiveWindow.View.ShowFieldCodes = True

End Sub

How to Hide Field codes in a Word Document using VBA

Word VBA – Hide Field Codes

The following snippet will hide the field codes present in Word document.

Sub Hide_Field_Codes()

Application.ActiveWindow.View.ShowFieldCodes = False

End Sub

Wednesday, December 24, 2008

Convert Symbols to Entities using Word VBA

Word VBA Symbols to Entities Conversion Program



Symbols when converted to Text (Save as Text) seldom retain the original shape. It has been a practice to convert these symbols to entities (mostly the symbol name prefixed with an ampersand and followed by a semi colon), for example, α † etc



The following code expects a tab separated text file with symbol’s character code and its corresponding entity representation. For example



176 & degree;


945 & alpha;



To know about the corresponding character code for a symbol, you can use Alt + Symbol Key. For example Alt + 0151 will give an emdash etc



Or you can check from Insert -- > Symbol

Word Insert Symbol Dialog





We read the text file using FileSystemObject’s OpenTextFile (Refer )



Set oFil = oFS.OpenTextFile("c:\testasc.txt")



and uses the Split Function to convert each line to an array of two elements and iterate through the document



Sub Convert_Symbols2Entities()



Dim MyString


Dim arFindReplace


Dim oFS As Object



On Error GoTo Err_Found



Selection.HomeKey wdStory, wdMove



Set oFS = CreateObject("Scripting.FileSystemObject")



Set oFil = oFS.OpenTextFile("c:\testasc.txt")



Do Until oFil.AtEndOfStream ' Loop until end of file.



MyString = oFil.ReadLine



' Report if the Input is not Tab Separated


If InStr(1, MyString, Chr(9)) = 0 Then


Open ActiveDocument.Path & "\" & "SymbolsError.txt" For Append As 3


Print #3, MyString & " not replaced"


Close #3


GoTo TakeNext


End If



' Split the Input to Find & Replace Text


arFindReplace = Split(MyString, Chr(9))



' Report if ASCII Value is not valid


If Val(arFindReplace(0)) = 0) Then '' Then


Open ActiveDocument.Path & "\" & "SymbolsError.txt" For Append As 3


Print #3, MyString & " ASCII Value not valid"


Close #3


GoTo TakeNext


End If



Selection.Find.ClearFormatting



Selection.HomeKey wdStory, wdMove


With Selection.Find


.Text = ChrW(Val(arFindReplace(0)))


.Replacement.Text = arFindReplace(1)


End With


Selection.Find.Execute Replace:=wdReplaceAll



TakeNext:


Loop



LastCommands:


Close #1 ' Close file.


If Not oFS Is Nothing Then Set oFS = Nothing



Exit Sub


Err_Found:


' ----------------------------


' Error Handling


' ----------------------------


If Err <> 0 Then


Debug.Assert Err.Number <> 0


MsgBox Err.Number & " " & Err.Description & " has occurred", vbCritical, "ASCII Convert"


Err.Clear


GoTo LastCommands


End If



The code uses ChrW function, which returns a String containing the Unicode character except on platforms where Unicode is not supported




Tuesday, December 16, 2008

How to check if Selection is Within a Table using Word VBA?

How to check if Range is Within a Table using Word VBA?

I was perplexed when LakshmiSatish, a wonderful copyeditor (and a great person) instructed some rules to be applied quite differently when a selected text is within a Table. Hats-off to copyeditors; you guys simply do a great job; I am afraid if the reader will know the hard-work you put. Enough musings! How to check if our Selection.Find is inside a Word Table? The following code makes that easy

Sub Check_If_Selection_Within_Table()

If Selection.Information(wdWithInTable) = True Then

MsgBox "Selection within Table"

Else

MsgBox "Selection outside Table"

End If

End Sub

Really easy isn’t it. There are also some other parts of Text that can be ignored. How ? Bookmarks is an easy way. We will deal with it soon.


Saturday, October 11, 2008

Manipulate ActiveX TextBoxes in a Word Document using VBA

Change Content of Embedded Textboxes in Word using VBA

Word Document might contain text boxes embedded in it as Inlineshapes. In that case, it can be manipulated using VBA as follows:

Sub Document_TextBoxes()

Dim oCtl As InlineShape

Dim oTB

For Each oCtl In ActiveDocument.InlineShapes

If oCtl.OLEFormat.ProgID = "Forms.TextBox.1" Then

Set oTB = oCtl.OLEFormat.Object

oTB.Text = "Sample Text"

End If

Next

End Sub




Embedded Text Box using Word VBA

Automatically Tag Underlined Words using Word VBA

Tag Formatted Text in Word using VBA

Here is a Word VBA snippet for searching text in a particular format, for example, underlined text and Tag them

Sub Tag_Under_Line()

Selection.ClearFormatting

Selection.HomeKey wdStory, wdMove

Selection.Find.Font.Underline = wdUnderlineSingle

Selection.Find.Execute ""

Do Until Selection.Find.Found = False

Selection.Font.Underline = wdUnderlineNone

Selection.InsertBefore "<>"

Selection.InsertAfter "< /UL >"

Selection.MoveRight

Selection.Find.Execute ""

Loop

End Sub


Word Document with Formatting (Underline)

(Tagged Word Document after Macro Execution)

Programmatically Delete Word Addins from the Addins List using VBA

Delete Word Addins using Word VBA


At times there will be quite a no of Addins that you would have tested in Word and they will line-up in the Addins List or you would have added no of versions of the same addin and it still is showing on the list

The following code will delete all uninstalled word addins from the Addins List

Private Sub Delete_UnInstalled_WordAddins()

Dim oAddin As AddIn

On Error GoTo Err_Addin

For Each oAddin In AddIns

If oAddin.Installed = False Then

oAddin.Delete

End If

Next oAddin

Finally:

If Not oAddin Is Nothing Then Set oAddin = Nothing

Err_Addin:

If Err < > 0 Then

Err.Clear

GoTo Finally

End If

End Sub

Uninstalled Word Addin

Word Addins Removed using VBA

UnInstall Word Addins using VBA


Here is a simple method to uninstall a Word Addin (.dot file) using Word VBA

Private Sub UnInstalled_AllWordAddins()

Dim oAddin As AddIn

On Error GoTo Err_Addin

For Each oAddin In AddIns

If oAddin.Installed Then

msg = oAddin.Name

oAddin.Installed = False

End If

Next oAddin

Finally:

If Not oAddin Is Nothing Then Set oAddin = Nothing

Err_Addin:

If Err < > 0 Then

Err.Clear

GoTo Finally

End If

End Sub


Installed Word Addin

Word Addin List after Macro Execution. Addin is uninstalled (not removed)

Programmatically Add Modules/Addins to Word using VBA

Install Word Addins using VBA


Here is a simple method to add a Word Addin (.dot file) using Word VBA

Private Sub Add_Word_Addin()

Dim oAddin As AddIn

On Error GoTo Err_Addin

' Add the Word Addin and Install It

Set oAddin = Application.AddIns.Add("c:\ShasurData\vbadud_Business_Template1.0.dot", True)

Finally:

If Not oAddin Is Nothing Then Set oAddin = Nothing

Err_Addin:

If Err < > 0 Then

Err.Clear

GoTo Finally

End If

End Sub



Word Addins Dialog Before Macro Execution

Word Addins Dialog After Macro Execution

Monday, March 31, 2008

Adding Images to Header using VBA (Word VBA)

Use Pictures/Images in Word Document Header using Word VBA

Most often we will be using company's logo in Header. Here is the way to do it using VBA

Sub Add_File_Header()

Set docActive = Word.ActiveDocument

ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.InlineShapes.AddPicture "C:\My Documents\My Pictures\MYPicture.bmp"

docActive.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader

ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text = "Header text" ' ERROR

objWord.ActiveDocument.ActiveWindow.View.SeekView = wdSeekMainDocument

With docActive.PageSetup

.DifferentFirstPageHeaderFooter = False 'Set this to false will put text on first page, else will not.

End With

End Sub

Updating Word Fields (VBA)

Using Word VBA to Update all Field Codes in Word Document


Here is a simple macro that will update all the fields in a Word document

Sub Update_Field()

ActiveWindow.ActivePane.View.Type = wdPrintView
Application.ScreenUpdating = True
Selection.WholeStory
ActiveDocument.Fields.Update

End Sub

Monday, December 03, 2007

Comparing two Word Documents using Word VBA

Compare Word Documents using VBA

Here is a simple routine, which will compare two Microsoft Word documents and return the status.


Sub IsDocument_Equal()

Dim oDoc1 As Word.Document
Dim oResDoc As Word.Document

' Delete the tables from both the document

' Delete the images from both the document

' Replace Paragraphs etc

Set oDoc1 = ActiveDocument

' comparing Document 1 with New 1.doc
oDoc1.Compare Name:="C:\New 1.doc", CompareTarget:=wdCompareTargetNew, DetectFormatChanges:=True

'This will be the result document
Set oResDoc = ActiveDocument

If oResDoc.Revisions.Count <> 0 Then
'Some changes are done
MsgBox "There are Changes "
Else
MsgBox "No Changes"
End If

End Sub

Run a Automatic Macro in Word Document

Execute Word Macro on File Open

There are numerous instances where one stores the word document format as a Microsoft Word template. When the user opens the document (using the template), some macro needs to be executed. This can be achieved by RunAutoMacro Method of Word VBA

Sub Run_Macro_In_WordDocument()

Dim oWD As Word.Document
Set oWD = Documents.Add("c:\dcomdemo\sample.dot")
oWD.RunAutoMacro wdAutoOpen

End Sub

Here a new document is open based on the Sample.dot template and once the document is open the AutoOpen macro is fired

RunAutoMacro Method can be used to execute an auto macro that's stored in the specified document. If the specified auto macro doesn't exist, nothing happens

On the other hand, if a normal macro (not auto open etc) needs to be executed, Run method can be used

Application.Run "Normal.FormatBorders"

Sunday, July 08, 2007

Get the Height & Width of Shapes / Figures in Word Document (Word VBA)

Height & Width of Shapes / InlineShapes in Word Document (Word VBA)

Figures are embedded in the word document and when they move they are a nemesis. Programmers are often given the job of aligning, resizing etc. Here is a simple example to get the height of the Shapes. Here you will notice that a particular inline shape has been singled out. You will get to know this if you run this in the document:)

Sub Figure_Attributes()
Dim sRep
sRep = ""
For I = 1 To ActiveDocument.InlineShapes.Count
If ((ActiveDocument.InlineShapes(I).Type > 0 And ActiveDocument.InlineShapes(I).Type <> 7 And ActiveDocument.InlineShapes(I).Type < 18)) Then
Height = ActiveDocument.InlineShapes(I).Height
Width1 = ActiveDocument.InlineShapes(I).Width
ActiveDocument.InlineShapes(I).Select
If Selection.Fields.Count = 0 Then
sRep = sRep & fname & vbTab & Height & vbTab & Width1 & vbCr
End If
End If
Next I
For I = 1 To ActiveDocument.Shapes.Count
Height = ActiveDocument.Shapes(I).Height
Width1 = ActiveDocument.Shapes(I).Width
ActiveDocument.Shapes(I).Select
sRep = sRep & fname & vbTab & Height & vbTab & Width1 & vbCr
Next I
MsgBox "Attributes of all the shapes in " & ActiveDocument.Name & vbCrLf & sRep
End Sub

Paragraph & Character Styles in Word Document (Word VBA)

Export Character Styles from Word Document / Export Paragraph Styles from Word Document

Here is the simple macro for extracting character & paragraph styles from a Word document. This exports the styles to a new word document



Sub Export_Styles_In_Document()

Dim oSource As Document
Dim oRep As Document
Dim oPara As Paragraph

Set oRep = Documents.Add



Set oSource = ActiveDocument
For I = 1 To oSource.Styles.Count
If oSource.Styles(I).Type = wdStyleTypeParagraph Then
SType = "Para"
oRep.Bookmarks("\EndOfDoc").Select
Set oPara = oRep.Paragraphs.Add
Set oPara = oRep.Paragraphs.Add
oPara.Range.Text = SType & ": " & oSource.Styles(I).NameLocal
Else
SType = "Char"
End If
Next I
For I = 1 To oSource.Styles.Count
If oSource.Styles(I).Type = wdStyleTypeParagraph Then
SType = "Para"
Else
SType = "Char"
oRep.Bookmarks("\EndOfDoc").Select
Set oPara = oRep.Paragraphs.Add
Set oPara = oRep.Paragraphs.Add
oPara.Range.Text = SType &amp; ": " & oSource.Styles(I).NameLocal
End If
Next I
oRep.Activate
End Sub


Saturday, May 26, 2007

Insert Procedure to a Module Using VBComponents

Insert Procedure to a Module Using VBComponents

Sub Insert_PRocedure_To_BasModule()

' This program will need reference to Microsoft Visual Basic for Extensibility Library

Dim VBP As VBProject
Dim VBC As VBComponent
Dim VBMod As CodeModule

' -----------------------------------------------------------
' Coded by Shasur for http://vbadud.blogspot.com
' -----------------------------------------------------------
Workbooks.Add
Set VBP = ActiveWorkbook.VBProject

Set VBC = VBP.VBComponents.Add(vbext_ct_StdModule)
VBC.Name = "MyMacro"

Set VBMod = VBC.CodeModule

VBMod.InsertLines 3, "Sub NewProc()" & Chr(13) & _
" Msgbox ""Welcome to VB Component Programming"" " & Chr(13) & _
"End Sub"

End Sub

Dynamic Insertion of Procedure Bas Module, Dynamic Creation of Function / Procedure in BAS/Class Module, Automatic Creation of Function / Procedure in BAS/Class Module, Create New Module using VBA, VBA Create Module, VBA Attach Module to Workbook
Related Posts Plugin for WordPress, Blogger...

Visual Basic for Applications (VBA) Forum (recent threads)

CodeKeep VBA Feed

Visual Studio Tools for Office Forum (recent threads)

Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.

Office Business Applications (OBA) Team Blog

MSDN Code Gallery Published Resources For Tag VSTO

microsoft.public.vsnet.vstools.office Google Group