How to get the paragraph number from a word document? - vba

I am trying to achieve the following requirement but I am not very well versed with word documents.
What I need to get is the paragraph number and page number a specific term appears. And this data should be made a table in Excel.
I am wondering if there is a possibility to get the para# from a word document from Excel VBA.

Imagining you are searching for the word "text", this is the word part.
With Selection.Find
.Execute FindText:="text"
End With
'paragraph number
parag = Selection.Range.Information(wdFirstCharacterLineNumber)
'page number
pg = Selection.Range.Information(wdActiveEndPageNumber)
In order to store this data in new excel workbook.
Set wb = Excel.Application.Workbooks.Add
wb.Sheets(1).Cells(1,1).Value = parag
wb.Sheets(1).Cells(1,2).Value = pg
Excel.Application.Visible = True
In word you would have to set a reference to Microsoft Excel 16.0 Object Library.

Related

VBA does not recognize the correct number of MS Word windows/documents open

Where I am working, we have software that converts an xml file into a word document. The only issue is that it can only do 1 xml file at a time, producing 1 word document at a time. I am trying to find a way to join all the word documents into 1. Here is the code I came up with.
Sub merge()
Dim myDoc As Documents
Dim count As Integer
Set myDoc = Documents
count = myDoc.count
If count <> 1 Then
For i = 1 To count - 1
myDoc(i).Select
Selection.WholeStory
Selection.Copy
myDoc(count).Range.Select
Selection.EndKey Unit:=wdLine
Selection.TypeParagraph
Selection.Paste
Next i
Else
MsgBox ("No other documents open")
End If
End Sub
The only issue I am running into is that when the software converts the xml file into a word document, the VBA does not recognize any of the converted documents even though it is open in MS Word. If I run code like "application.windows.count or documents.count" it will not recognize it. If I open any other document the code will merge everything together. But the converted documents from the software cannot be merged. Is there anything I can do to force MS Word to recognize the converted documents?

Finding Tables in Current Word Document

I'm trying to edit tables within a Word Document using VBA. The following MsgBox returns 0 even though there are several tables within the document. Elsewhere in the macro, I am successfully editing a value in the Word Document with:
With WA.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute Findtext:="Sally", ReplaceWith:=FirstName, Replace:=1
EndWith
EndWith
MsgBox (WA.ActiveDocument.Content.Tables.Count)
Just use inside the With statement(if they are actual tables)
MsgBox .Tables.Count
You can verify by switching to the Word document itself and putting the following Msgbox ActiveDocument.Tables.Count in the ThisDocument part of the ActiveDocument. If the answer is still 0 then you are not working with Word Tables.

Insert text after numbers and before words in a Word hierarchical heading

I am working my way through two books (Roman's Writing Word Macros, Mansfield's Mastering VBA for MS Office). In my work environment, I use both Word 2007 and Word 2010.
My issue is that I want to use VBA to insert a very brief amount of standardized text before the English-language string in my numbered hierarchical headings. For instance, I have:
1.1.1 The Quick Brown Fox.
What I want is:
1.1.1 (XXxx) The Quick Brown Fox.
I guess my most basic issue is that I don't know how to approach the situation. I have hierarchical headings yet I don't know how to say, in effect, "Go to each hierarchical heading regardless of level. Insert yourself in front of the first English language word of the heading. Paste the text "XXxx" in front of the first word in the heading. Go on to the next heading and all remaining headings and do the same. My document is over 700 pages and has hundreds of hierarchical headings.
I see that paragraphs are objects and that hierarchical headings are paragraphs. However, I can't see any way to make VBA recognize what I am talking about. I haven't been able to use Selection approaches successfully. I've tried using the Range approach but just have not been able to phrase the VBA code intelligently. I haven't been able to specify a range that includes all and only the hierarchical headings and, especially, I don't understand how to get the insertion to happen in front of the first English-language word of the heading.
I have just begun to look at using Bookmarks. However, don't bookmarks require me to go to every heading and enter them? I may as well just paste my content if that is the case. I'm stumped. It is interesting that in no way, as might have been expected, does this appear to be a simple matter
Assuming you are using Word's outline levels (I think this is what you mean by hierarchical headings), you can check a paragraph for this state. For example, assuming I have a paragraph in my document that has the Heading 1 style applied to it:
Sub PrintHeadings()
Dim objDoc as Document
Dim objPara as Paragraph
Set objDoc = ActiveDocument
For each objPara in objDoc.Content.Paragraphs
If objPara.OutlineLevel <> wdOutlineLevelBodyText then
Debug.Print objPara.Range.Text
End If
Next objPara
End Sub
This code would print the contents of any paragraph that has an outline level above body text to the VBA Immediate Window. There are other approaches as well; you could use Find and Replace to search for each of the Outline Levels. This gives you a bit less control; you'd want your change to be something that could be encapsulated in a Word Find and Replace. But, it would be faster if you have a long document and not too many heading levels. A basic example:
Sub UnderlineHeadings()
Dim objDoc as Document
Set objDoc = ActiveDocument
With objDoc.Content.Find
.ClearFormatting
.ParagraphFormat.OutlineLevel = wdOutlineLevel1
With .Replacement
.ClearFormatting
.Font.Underline = wdUnderlineSingle
End With
.Execute Forward:=True, Wrap:=wdFindContinue, Format:=True, Replace:=wdReplaceAll
End With
End Sub
That would underline all of your text of Outline Level 1.
Perhaps that will get you started.
I asked this question some months ago: "My issue is that I want to use VBA to insert a very brief amount of standardized text before the English-language string in my numbered hierarchical headings." By "numbered hierarchical headings" I meant Word multilevel lists. The answers I received were appreciated but did not respond effectively to my question or guide me to a resolution. I pass this along in the hope it may be of use to others.
First, the "number" part of the Word heading is irrelevant. In writing your code, there is NO need to think of a "number" portion and a "text" portion of the heading. I was afraid that any text I was trying to insert would be inserted BEFORE the multilevel numbering rather than BEFORE the English language text. The multilevel numbering is apparently automatically ignored. Below are two solutions that worked.
This first macro succeeded in producing the desired result: 1.1.1 (FOUO). I used this macro to create individual macros for each order of heading. I haven't learned how to combine them all into one macro. But they work individually (but not without the flaw of taking too much time ~5 to 10 minutes for a complex, paragraph-heavy 670 page document).
Public Sub InsertFOUOH1()
Dim doc As Document
Dim para As Paragraph
Dim paraNext As Paragraph
Dim MyText As String
Dim H1 As HeadingStyle
Set doc = ActiveDocument
Set para = doc.Paragraphs.First
Do While Not para Is Nothing
Set paraNext = para.Next
MyText = "(U//FOUO) "
If para.Style = doc.Styles(wdStyleHeading1) Then
para.Range.InsertBefore (MyText)
End If
Set para = paraNext
Loop
End Sub
THIS WORKS ON ALL FIRST ORDER HEADINGS (1, 2, 3 ETC.)
I used the macro below to add my security marking all body paragraphs:
Public Sub InsertFOUObody()
'Inserts U//FOUO before all body paragraphs
Dim doc As Document
Dim para As Paragraph
Dim paraNext As Paragraph
Dim MyText As String
Set doc = ActiveDocument
Set para = doc.Paragraphs.First
Do While Not para Is Nothing
Set paraNext = para.Next
MyText = "(U//FOUO) "
If para.Style = doc.Styles(wdStyleBodyText) Then
para.Range.InsertBefore (MyText)
End If
Set para = paraNext
Loop
End Sub
These macros are running slowly and, at the end, generating Error 28 Out of stack space errors. However the error is displayed at the end of running the macros and after the macros have successfully performed their work.

Error 1004 with VBA code with bookmarks

I am using a macro to populate a word document with text from named ranges in excel. The word document has bookmarks that correspond with the named excel ranges. I did not write the code, but rather copied it from another source.
There is quite a bit more to this macro than the snippet I posted. I could post the rest if that is useful. I had about half of my word document bookmarked and the macro was working fine then it suddenly stopped working.
I am receiving a error 1004 in the line highlighted below. I am a newbie so I'm not even quite sure what I should be searching for to fix this issue. Any assistance you could provide would be appreciated! Thanks in advance!
P.S. In case it's relevant, I am using Word and Excel 2007
'PASTE TEXT STRINGS LOOP
n = 1
For Each temp In BkmTxt
p = p + 1
Prompt = "Please wait. Copying text. Carrying out operation " & p & " of " & pcount & "."
Application.StatusBar = Prompt
'If The Bkmtxt(n) is empty then go to the next one, once that has been found do next operation.
If BkmTxt(n) = Empty Then
n = n + 1
'should find match and work
Else
'You might want to use multiple copies of the same text string.
'In this case you need to call the bookmark as follows: "ARTextWhatever_01"
'You can use as many bookmarks as you want.
BkmTxtSplit = Split(BkmTxt(n), "_")
vValue = Range(BkmTxtSplit(0)).Text **<----- ERROR HERE**
Set wdRng = wdApp.ActiveDocument.Bookmarks(BkmTxt(n)).Range
If Len(sFormat) = 0 Then
'replace the bookmark text
wdRng.Text = vValue
Else
'replace the bookmark text with formatted text
wdRng.Text = Format(vValue, sFormat)
End If
'Re-add the Bookmark
wdRng.Bookmarks.Add BkmTxt(n), wdRng
n = n + 1
End If
Next
Step 1: Don't copy code from external sources. Use external sources as a learning tool and try to understand what they are actually doing.
Now if I understand you correctly, you simply have an Excel sheet with named ranges, I assume they have information already within them, and a word document with bookmarks that EXACTLY match the named ranges:
Step 2: Make sure you have the word object library reference within excel
Here:
sub KeepItDoin()
dim xlRange as Excel.Range
dim wdApp as new Word.Application
dim wdDoc as Word.Document
dim wdBkm as Word.Bookmark
set wdDoc = wdApp.Documents.Open( "Filepath" ) 'get filepath from where ever
for each wdBkm in wdDoc.Bookmarks
set xlRange = Application.Range(wdBkm.Name)
wdBkm.range.text = xlRange.Value
next wdBkm
end sub
That will get you close probably (didn't test, don't care if it works. Use it to learn). The idea is that if the bookmarks match up to the range, we can use their names to find the ranges in excel and then tell excel to move the data within it into the bookmarks range.
You will likely need to add some formatting or maybe create a table and then move cell by cell in the range and fill the table but this is as close as I'm willing to get since you like to copy pasta.
In case anyone is interested, I figured it out. There was an error with the bookmarks I inserted into my Word document. This macro returns Error 1004 if the word document contains a bookmark that does not correspond to a range in excel. Thank you for your help.

Changing paragraph alignment of word document through VBA

I Have excel workbook which maintains data of my customers Like address & Due amount. I am writing a VBA code in excel which will generate letter to each of the customer for the due amounts. I cannot use mailmerge because of the complexity of the letter. I am using following codes to add paragraphs
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Add
wrdDoc.content.InsertAfter "----------"
wrdDoc.content.InsertParagraphAfter
Now I need to change alignment of paragraphs. The paragraphs in body of letter are to be justified while some paragraphs like subject line are to be center aligned. I tried this code but its not working
1.
wrdDoc.Paragraphs(8).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
also
2.
wrdDoc.Paragraphs(8).Alignment = wdAlignParagraphCenter
What is the correct way doing this?
Regards
Shekhar
This worked for me:
objselection.Paragraphs.Alignment = 3
Numbers:
3 Justify
2 Center
1 Right Justify