This ChatGPT generated code converts text starting with pattern "###" to style "Heading 1".
Sub TripleHash2H1()
Dim oRange As Range
Dim searchText As String
searchText = "###"
Set oRange = ActiveDocument.Range
With oRange.Find
.Text = searchText
.Style = "Normal"
.Replacement.Text = ""
.Replacement.Style = "Heading 1"
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
End With
End Sub
This macro works but:
.Replacement.Text = ""
and .Replacement.Style = ..
only replace formatting. It's same asChange:
Option Explicit
Sub TripleHash2H1()
Dim oRange As Range
Dim searchText As String
Dim targetStyle As String
targetStyle = "Heading 1"
searchText = "###"
Set oRange = ActiveDocument.Range
With oRange.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = searchText
.Style = "Normal"
.Replacement.Style = targetStyle
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
.ClearFormatting
.Replacement.ClearFormatting
.Style = targetStyle
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
End With
End Sub
Update:
Option Explicit
Sub TripleHash2H1()
Dim oRange As Range
Dim searchText As String
Dim targetStyle As String
Dim bMatch As Boolean
targetStyle = "Heading 1"
searchText = "###[!#]"
Set oRange = ActiveDocument.Range
With oRange.Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = True
.MatchWholeWord = False
.Forward = True
.Wrap = wdFindStop
.Text = searchText
.Style = "Normal"
Do While .Execute
' oRange.Select
If oRange.Paragraphs(1).Range.Start = oRange.Start Then
If oRange.Start = 0 Then
bMatch = True
Else
bMatch = Not (ThisDocument.Range(oRange.Start - 1, oRange.Start).Text = "#")
End If
If bMatch Then
oRange.Text = Right(oRange.Text, 1)
oRange.Expand unit:=Word.wdParagraph
oRange.Style = targetStyle
End If
End If
oRange.Collapse Word.wdCollapseEnd
Loop
End With
End Sub