List all instances of the "Heading 1" style - vba

I'm trying to list every instance of the "Heading 1" style within my document (to eventually list them in a combobox on a form).
The following code appears to find the instances of "Heading 1", as there are the correct number of entries listed within the Immediate Window, but .text is returning nothing.
What am I doing wrong? Thanks.
Dim blnFound As Boolean
Dim i as Integer
i = 1
With ThisDocument.Range.Find
.Style = "Heading 1"
Do
blnFound = .Execute
If blnFound Then
Debug.Print i & " " & .Text
i = i + 1
Else
Exit Do
End If
Loop
End With

I don't believe the object you have has a .Text property. Selection has a .Text property. Try this:
Sub FindHeadings()
' October 28, 2014
Dim blnFound As Boolean
Dim i As Integer
i = 1
' Set up the find conditions
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Style = ActiveDocument.Styles("Heading 1")
With Selection.Find
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.MoveLeft Unit:=wdCharacter, count:=1
'Repeat while you find the style
blnFound = True
While blnFound
With Selection.Find
.Execute
If .Found = True Then
Debug.Print i & " " & Selection.Text
i = i + 1
' Move to the next character
Selection.MoveRight Unit:=wdCharacter, count:=1
Else
Debug.Print "Done"
blnFound = False
End If
End With
Wend
End Sub

Related

Remove OR replace faulty paragraph marks using VBA macro

I have some faulty paragraphs, which are causing my other macros to not work properly.
They are usually heading style 2, style 3
Empty (not sure)
before OR after table (not sure)
surrounded by dotted line
causes the heading and next table to merged together (not sure)
I tried to replace/removed those with the following macro:
Sub HeadingParaBug()
Dim H As Range
Set H = ActiveDocument.Range
LS = Application.International(wdListSeparator)
With H.Find
.Text = "^p "
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
.Text = " ^p"
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
.Text = "^p ^p"
.Replacement.Text = "^p^p"
.Execute Replace:=wdReplaceAll
.Text = "^13{2" & LS & "}"
.Replacement.Text = "^p"
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
.Text = ""
.Style = wdStyleHeading2
.MatchWildcards = False
Do While .Execute
If H.Text <> vbCr Then
H.Collapse 0
H.Select
H.InsertParagraph
H.Delete
End If
H.Collapse 0
Loop
End With
Set H = ActiveDocument.Range
With H.Find
.Style = wdStyleHeading3
Do While .Execute
If H.Text <> vbCr Then
H.Collapse 0
H.Select
H.InsertParagraph
H.Delete
End If
H.Collapse 0
Loop
End With
End Sub
But somehow, it do not completely removed/replace the faulty paragraph marks. The above macro finds those paragraphs, add new and then remove it. which eventually removed the dotted line.
Can anybody explain this phenomena? what is the right ways to remove/replace those paragraphs. please download and see test file with error on page 7
Update: Even I tried with the following code but it did nothing (on MacOS Video). I think it is not finding the hidden paragraphs:
Sub HidNempty()
Dim H As Range
Set H = ActiveDocument.Range
With H.Find
.Text = "^p "
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
.Text = " ^p"
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
.Text = "^p ^p"
.Replacement.Text = "^p^p"
.Execute Replace:=wdReplaceAll
.Text = "^p"
Do While .Execute
If H.Font.Hidden = True Then
H.Font.Hidden = False
If Len(Trim(H.Paragraphs(1).Range.Text)) = 1 Then
H.Delete
End If
End If
Loop
End With
End Sub
To unhide all document paragraphs, please try the next piece of code:
Sub UnHideParagraphs()
Dim para As Paragraph
For Each para In ActiveDocument.Paragraphs
If para.Range.Font.Hidden Then
para.Range.Font.Hidden = False
End If
Next para
End Sub
It should work even if only part of the paragraph range is hidden...
Find/Replace won't delete duplicate paragraph breaks before a table, between tables, or after a table. Try:
Sub Demo()
Application.ScreenUpdating = False
Dim LS As String, Tbl As Table, bHid As Boolean
LS = Application.International(wdListSeparator)
bHid = ActiveWindow.View.ShowHiddenText
ActiveWindow.View.ShowHiddenText = True
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = True
.Forward = True
.Replacement.Font.Hidden = False
.Wrap = wdFindContinue
.MatchWildcards = False
.Text = "^p^w"
.Replacement.Text = "^p"
.Execute Replace:=wdReplaceAll
.Text = "^w^p"
.Execute Replace:=wdReplaceAll
.MatchWildcards = True
.Text = "^13{2" & LS & "}"
.Execute Replace:=wdReplaceAll
.Wrap = wdFindStop
End With
Do While .Find.Execute = True
With .Duplicate
.Font.Hidden = False
.Start = .Start + 1
.Text = vbNullString
End With
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
For Each Tbl In ActiveDocument.Range.Tables
With Tbl.Range
Do While .Characters.First.Previous.Previous = vbCr
.Characters.First.Previous.Previous = vbNullString
Loop
.Characters.First.Previous.Font.Hidden = False
Do While .Characters.Last.Next = vbCr
If .Characters.Last.Next.End = ActiveDocument.Range.End Then Exit Do
If .Characters.Last.Next.Next.Information(wdWithInTable) = True Then Exit Do
.Characters.Last.Next = vbNullString
Loop
.Characters.Last.Next.Font.Hidden = False
End With
Next
ActiveWindow.View.ShowHiddenText = bHid
Application.ScreenUpdating = True
End Sub
You will observe various lines in the code that apply .Font.Hidden = False. Depending on what you're trying to achieve visually, you may or may not want those.

Issue regarding deleting paragraphs

I refer to a code from :https://www.datanumen.com/blogs/quickly-find-delete-paragraphs-containing-specific-texts-word-document/
However, I can only delete the heading rather than the whole paragraph(heading + content). I've tried several methods but it still not work...please help me with this, thanks!
Sub DeleteParagraphsContainingSpecificTexts()
Dim strFindTexts As String
Dim strButtonValue As String
Dim nSplitItem As Long
Dim objDoc As Document
strFindTexts = InputBox("Enter texts to be found here, and use commas to separate them: ", "Texts to be found")
nSplitItem = UBound(Split(strFindTexts, ","))
With Selection
.HomeKey Unit:=wdStory
' Find the entered texts one by one.
For nSplitItem = 0 To nSplitItem
' Find text in Heading1
With Selection.Find
.ClearFormatting
.Text = Split(strFindTexts, ",")(nSplitItem)
.Style = wdStyleHeading1
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchWholeWord = False
.MatchCase = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found = True
' Expand the selection to the entire paragraph.
Selection.Expand Unit:=wdParagraph
strButtonValue = MsgBox("Are you sure to delete the paragraph?", vbYesNo)
If strButtonValue = vbYes Then
Selection.Delete
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
' Find text in Heading2
With Selection.Find
.ClearFormatting
.Text = Split(strFindTexts, ",")(nSplitItem)
.Style = wdStyleHeading2
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchWholeWord = False
.MatchCase = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found = True
' Expand the selection to the entire paragraph.
Selection.Expand Unit:=wdParagraph
strButtonValue = MsgBox("Are you sure to delete the paragraph?", vbYesNo)
If strButtonValue = vbYes Then
Selection.Delete
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
' Find text in Heading3
With Selection.Find
.ClearFormatting
.Text = Split(strFindTexts, ",")(nSplitItem)
.Style = wdStyleHeading3
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchWholeWord = False
.MatchCase = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchAllWordForms = False
.Execute
End With
Do While .Find.Found = True
' Expand the selection to the entire paragraph.
Selection.Expand Unit:=wdParagraph
strButtonValue = MsgBox("Are you sure to delete the paragraph?", vbYesNo)
If strButtonValue = vbYes Then
Selection.Delete
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
Next
End With
MsgBox ("Word has finished finding all entered texts.")
Set objDoc = Nothing
End Sub
The problem isn't the code, it is your understanding of what a paragraph is. In your example each line of text is a paragraph.
From your description what you are trying to do is delete blocks of content under a heading containing a keyword, or in Word terminology "a Heading Level". The following code should work for you:
Sub DeleteParagraphsContainingSpecificTexts()
Dim strFindTexts As String
Dim strButtonValue As String
Dim nSplitItem As Long
Dim objDoc As Document
strFindTexts = InputBox("Enter texts to be found here, and use commas to separate them: ", "Texts to be found")
nSplitItem = UBound(Split(strFindTexts, ","))
' Find the entered texts one by one.
For nSplitItem = 0 To nSplitItem
DeleteHeadingBlock Split(strFindTexts, ",")(nSplitItem), wdStyleHeading1
DeleteHeadingBlock Split(strFindTexts, ",")(nSplitItem), wdStyleHeading2
DeleteHeadingBlock Split(strFindTexts, ",")(nSplitItem), wdStyleHeading3
Next
End Sub
Public Sub DeleteHeadingBlock(ByVal headingText As String, headingStyle As WdBuiltinStyle)
Dim hdgBlock As Range
With ActiveDocument.Content
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = headingText
.Style = headingStyle
.Replacement.Text = ""
.Forward = True
.Format = True
.Wrap = wdFindStop
End With
Do While .Find.Execute
Set hdgBlock = .GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")
hdgBlock.Delete
Loop
End With
End Sub

Highlight text from one open parenthesis to the next open parenthesis

My goal is to highlight text from one open parenthesis to the next open parenthesis, if there is no closed parenthesis between them.
Sub HighlightNestedParentheses()
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
Options.DefaultHighlightColorIndex = wdGray50
With Selection.Find
.Text = "\([!\)]#\("
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
The macro above works when the Word file contains the following text:
text (text (text
However, there is an infinite loop when the document contains a single open parenthesis:
text (text
I prefer to not highlight any text in this second case.
Try:
Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "\(*\)"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
End With
Do While .Find.Execute
With .Duplicate
Set Rng = .Characters.Last
Do While InStr(2, .Text, "(", vbTextCompare) > 0
.MoveEndUntil ")", wdForward
.End = .End + 1
.Start = .Start + 1
.MoveStartUntil "(", wdForward
Set Rng = .Characters.Last
Loop
End With
.End = Rng.End
.HighlightColorIndex = wdGray50
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
End Sub
For your revised description:
Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range
With ActiveDocument.Range
Set Rng = .Duplicate
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "("
.Replacement.Text = ""
.Forward = False
.Wrap = wdFindStop
.Format = False
.MatchWildcards = False
End With
Do While .Find.Execute
Rng.Start = .Start + 1
With Rng
If InStr(.Text, ")") = 0 Then
.HighlightColorIndex = wdBrightGreen
Else
.MoveEndUntil ")", wdBackward
If InStr(.Text, "(") = 0 Then
.MoveEndUntil "(", wdBackward
.HighlightColorIndex = wdBrightGreen
End If
End If
End With
.Collapse wdCollapseStart
Loop
End With
Application.ScreenUpdating = True
End Sub

Style to a variable in VBA

so i have this code, it replaces every X in the text with "Asunto (1,2,..): Expediente N°". I try to style this part of the code:
What i want is put that text that replaces the X in Arial 11 Bold
.Text = "Asunto" & " " & i & " " & "Expediente N°"
i tried this but the style applies to the whole document instead of just that text, i don´t know what else to try
Sub Macro1()
'
' Macro1 Macro
'
'
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "X"
.Replacement.Text = ""
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
i = i + 1
.Text = "Asunto" & " " & i & " " & "Expediente N°"
.Find.Execute
.Collapse wdCollapseEnd
.Find.Execute
Loop
With .Font
.Bold = True
.Name = "Arial"
.Size = 11
End With
Application.ScreenUpdating = True
MsgBox i & " Coincidencias."
End With
End Sub
You are NOT applying a Style - all you're doing is overriding whatever Style is already present with hard formatting. Do do with a Style, try for example:
Sub Demo()
Application.ScreenUpdating = False
Dim i As Long
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "X"
.Replacement.Text = ""
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
End With
Do While .Find.Execute
i = i + 1
.Text = "Asunto" & " " & i & " " & "Expediente N°"
.Style = wdStyleStrong
.Collapse wdCollapseEnd
Loop
End With
Application.ScreenUpdating = True
MsgBox i & " instances found."
End Sub
In the above, I've employed Word's 'Strong' Style, via the constant wdStyleStrong. If your text is already 11pt Arial, that's all you need. Otherwise, you should define a suitable 11pt Arial Bold character Style and apply that.

Word Macro VBA Finding specific style/list and converting to text

I am trying to use a Word Macro to select all text with the style "Number_List" and call the .ConvertNumbersToText function on it. I am having trouble only finding the list or that specific style.
Dim selBkUp As Range
Set selBkUp = ActiveDocument.Range(ActiveDocument.Range.Start, ActiveDocument.Range.End)
With ActiveDocument.Range.Find
.Style = ActiveDocument.Styles("Number_List")
.Forward = True
.Wrap = wdFindContinue
Dim SearchSuccessful As Boolean
SearchSuccessful = .Execute
If SearchSuccessful Then
selBkUp.Select
Selection.Range.ListFormat.ConvertNumbersToText
Else
' code
End If
End With
I select the entire document and covert all of the lists numbers to text, but I am trying to only select ones with that specific style or avoid the other 5 styles that may or may not be present. Any help would be appreciated!
The following code will search for one style and, if found, will convert to another style. Below this code is another subroutine that will list all styles found in a document.
' From http://forums.codeguru.com/showthread.php?448185-Macro-to-Change-Styles-in-Word
' This code will search for a specified Style and convert that to another Style
Sub FindReplaceStyle()
Selection.HomeKey wdStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Style = "Normal" ' Look for 'Normal'
'.Text = ""
.Replacement.Style = "Heading 1" ' Change to 'Heading 1'
' .Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Do While Selection.Find.Execute()
If Selection.Start = Selection.Paragraphs.First.Range.Start Then
Selection.Style = "Heading 1"
End If
Selection.Collapse wdCollapseEnd
Loop
End Sub
The code below will produce a list of all styles found in a document.
Also, I get an error trying to use your "Number_List"
' Following code from: http://www.vbaexpress.com/forum/showthread.php?41125-How-to-get-all-the-applied-Paragraph-Styles-of-a-document
Sub GetActiveStyles()
Application.ScreenUpdating = False
Dim RngStory As Range, oSty As Style, StrType As String, StrStyles As String
With ActiveDocument
For Each oSty In .Styles
For Each RngStory In .StoryRanges
With RngStory.Find
.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Style = oSty.NameLocal
.Forward = True
.Wrap = wdFindStop
.Format = True
.Execute
If .Found Then
Select Case oSty.Type
Case wdStyleTypeCharacter: StrType = "Character"
Case wdStyleTypeList: StrType = "list"
Case wdStyleTypeParagraph: StrType = "Paragraph"
Case wdStyleTypeTable: StrType = "Table"
End Select
StrStyles = StrStyles & oSty.NameLocal & " (" & StrType & ")" & vbCr
Exit For
End If
End With
Next RngStory
Next oSty
End With
Debug.Print StrStyles
'MsgBox StrStyles
Application.ScreenUpdating = True
End Sub