user1979270
user1979270

Reputation:

Change one letter color in VB Ms Word 2007

I'm new in Visual basic and I would like to approach something simple.

I have button and TextBox


Button:

    Private Sub CommandButton1_Click()
    TextBox1.Text = "Hi my name is Koki"
    End Sub

TextBox:

    Private Sub TextBox1_Change()
    End Sub

Output:

enter image description here

Note: It will help me even if there is a static solution, something like <span></span> in Html

Upvotes: 1

Views: 1345

Answers (1)

user2480047
user2480047

Reputation:

While dealing with VBA you have to consider ranges and then properties of the given ranges. Here you have a sample code doing what you want:

Private Sub CommandButton1_Click()

    Set Object = ActiveDocument.Shapes.AddTextbox(Orientation:=msoTextOrientationHorizontal, Left:=10, Top:=10, Width:=80, Height:=80)

    With Object.TextFrame.TextRange
        .Text = "Hi my name is Koki"
        With .Characters(2).Font
            .ColorIndex = wdTurquoise  'http://msdn.microsoft.com/en-us/library/office/aa195611(v=office.11).aspx
        End With
        With .Characters(12).Font
            .ColorIndex = wdTurquoise
        End With
        With .Characters(18).Font
            .ColorIndex = wdTurquoise
        End With
    End With

End Sub

As you can see, I am adding the textbox at the start. I am doing this to make sure that you use the right textBox (if you add an ActiveX textbox the behaviour would be different).

---------- UPDATE

In order to rely on the proposed methodology, you might have to use the Document Open event to delete any shape and write the ones you want. For example:

Private Sub Document_Open()

    For i = ActiveDocument.Shapes.Count To 1 Step -1
        ActiveDocument.Shapes(i).Delete
    Next i

    Set Object = ActiveDocument.Shapes.AddTextbox(Orientation:=msoTextOrientationHorizontal, Left:=10, Top:=10, Width:=80, Height:=80)

End Sub

This code will be called when the document is opened and will delete all the shapes you created (not the ActiveX objects, like the commandButton) and add the textbox. You can declare the Object variable globally and access it from anywhere in the code (CommandButton1_Click(), for example).

Bear in mind that this is an example of a workaround to get what you want. You don't need to delete the given shapes, you can just take this code to check what to do at the start of the document: if there is a shape called "the name I want", let it there and don't do anything, just set it to the global Object variable, that is:

Private Sub Document_Open()

    For i = ActiveDocument.Shapes.Count To 1 Step -1
        If(ActiveDocument.Shapes(i).Name = "the name I want") Then
          Set Object = ActiveDocument.Shapes(i)
          Exit Sub
        End If
    Next i

    Set Object = ActiveDocument.Shapes.AddTextbox(Orientation:=msoTextOrientationHorizontal, Left:=10, Top:=10, Width:=80, Height:=80)

End Sub

Upvotes: 1

Related Questions