PDA

View Full Version : [SOLVED:] Using a string in a line of code



Roderick
03-29-2019, 09:39 AM
The following link refers to a post I made last year:

http://www.vbaexpress.com/forum/showthread.php?63311-Writing-correct-string-syntax&highlight=

..about writing correct syntax.

I'm still plagued by this challenge and would appreciate some clarification if posible, please.

This is the code I have at the moment:

Dim Rng As Range, Lvl As Long
Dim myBuiltInHeading1 As String
Application.ScreenUpdating = False
myBuiltInHeading1 = Split(ActiveDocument.Styles(wdStyleHeading1).NameLocal, " ")(0)

With Selection
Set Rng = .Range
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:="\HeadingLevel")

Lvl = VBA.Right(Rng.Paragraphs.First.Style, 1)

.Fields.Add Range:=.Range, Type:=wdFieldEmpty, Text:="StyleRef ""Heading " & Lvl & """ \s", PreserveFormatting:=False


As can be seen, I have a string which shows the name of the built-in heading for the template (myBuiltInHeading1). What I would like to do is replace the string name into the last line of the shown procedure where it says "Heading".

I have tried adding and removing the double quotes plus adding Chr(34) characters to resolve the problem but they all give rise to an error. I know there is a combination but for the life of me I cannot seem to get the right mixture.

Could someone put me on the straight and narrow, please.

Thanks for the help.

Roderick

macropod
03-29-2019, 02:13 PM
You could use:

.Fields.Add Range:=.Range, Type:=wdFieldEmpty, Text:="StyleRef " & Chr(34) & "Heading " & Lvl & Chr(34) & " \s", PreserveFormatting:=False
However, you should also be aware that the
StyleRef field has no \s switch.

Roderick
03-30-2019, 01:48 AM
Thanks very much for your reply and advice.

Works as required.

Roderick