PDA

View Full Version : Search an expression (code) and turn the whole line into heading



SuperDocT
04-17-2023, 10:12 PM
Hi, I look for the correct Macro Code in order to search into the whole document for a certain code and turn the whole line into heading 6
I precise that the line containing the code can be in any format (heading/normal etc...)
This is the code I wrote and obviously doesn't work:


Sub head6_to_heading()
Dim doc As Word.Document
Dim rng As Word.Range
Set doc = ActiveDocument
Set rng = doc.Content
With rng.Find
.Text = "(head-"
.MatchCase = False
.MatchWholeWord = False
.Replacement.Style = doc.Styles("Heading 6").ParagraphFormat
.Wrap = wdFindStop
End With
End Sub

Thanks by advance

ruthburks
02-04-2024, 04:02 PM
Hello, you can try this code: geometry dash scratch (https://geometrydash-scratch.com)

Sub head6_to_heading()
Dim doc As Word.Document
Dim rng As Word.Range
Set doc = ActiveDocument
Set rng = doc.Content
With rng.Find
.Text = "(head-"
.MatchCase = False
.MatchWholeWord = False
.Wrap = wdFindStop
Do While .Execute
rng.Paragraphs(1).Range.Style = doc.Styles("Heading 6")
Loop
End With
End Sub

lilyttauer
08-12-2024, 01:13 AM
The issue with your code is that Find only searches for the complete text at once. Here's an improved macro that iterates through lines and checks for the code:


Sub Head6_To_Heading()
Dim doc As Word.Document
Dim rng As Word.Range
Dim para As Word.Paragraph
Dim foundText As String
Set doc = ActiveDocument
foundText = "(head-" ' Code to search for
For Each para In doc.Paragraphs
' Check if line contains the code
If InStr(para.Text, foundText) > 0 Then
Set rng = para.Range
' Apply Heading 6 style
rng.Style = doc.Styles("Heading 6")
Exit For ' Stop after finding the first occurrence (modify if needed)
End If
Next para
End Sub