Log in

View Full Version : how to Replace the Text in Word document



sateesh j
01-09-2014, 03:59 AM
hi to all

This is Satish,new to VBA in word, i am creating userform in word document to update the data in specific place. am almost inset the data, but i cann't replace the data.

when i submit the data data is inserting in-fornt of previous data.
i want only insert new data, by replace the previous data.
here is my code



Private Sub CommandButton1_Click()
Dim Name As Range
Set Name = ActiveDocument.Bookmarks("GreetName").Range
Name.Text = Replace(Me.Gname.Value)


Dim Address As Range
Set Address = ActiveDocument.Bookmarks("ToAdd").Range
Address.Text = Me.Taddress.Value


Dim dt As Range
Set dt = ActiveDocument.Bookmarks("Date").Range
dt.Text = Me.TDate.Value


Thanks for advance

macropod
01-09-2014, 04:32 AM
To be able to update the bookmark, you need to expend its range to include the inserted text. Your present code merely inserts the text after the bookmark. Try:

Private Sub CommandButton1_Click()
Call UpdateBookmark("GreetName", Me.Gname.Value)
Call UpdateBookmark("ToAdd", Me.Taddress.Value)
Call UpdateBookmark("Date", Me.TDate.Value)
End Sub
'
Sub UpdateBookmark(StrBkMk As String, StrTxt As String)
Dim BkMkRng As Range
With ActiveDocument
If .Bookmarks.Exists(StrBkMk) Then
Set BkMkRng = .Bookmarks(StrBkMk).Range
BkMkRng.Text = StrTxt
.Bookmarks.Add StrBkMk, BkMkRng
End If
End With
Set BkMkRng = Nothing
End Sub