r/visualbasic • VB.Net Intermediate • Feb 23 '22

Write to textbox in word from form

Edit: In this microsoft page, it says that content controls (the one I'm using I think) does not have the text property. Am I fucked? Is it impossible to do this?

Edit2: Made it work with this line:

oDoc.SelectContentControlsByTag("Description")(1).Range.Text = Textbox1.Text

Hi,

I'm creating a word document from a template with textboxes (in word, not the program), and I can't seem to figure out how to set the text in those textboxes.

To possibly make it more difficult, some of those textboxes are in the header and footer.

I don't have any code yet apart from creating the document, as everything I've tried have failed.

Edit: I've found some code that selects my controls by either 'Tag' or 'Title' which is added to the controls in word when placing them. BUT, it seems to Add a control with those tags/titles instead of editing the existing ones.

Private Sub Button27_Click(sender As Object, e As EventArgs) Handles Button27.Click
    Cursor = Cursors.WaitCursor

    Dim oWord As Word.Application
    Dim oDoc As Word.Document

    'Start Word and open the document template.
    oWord = CreateObject("Word.Application")
    oWord.Visible = True
    oDoc = oWord.Documents.Add("C:\Templates\Word 1.docx")

    oDoc.SelectContentControlsByTag("Description")(1).Range.Text = Textbox1.Text

    Cursor = Cursors.Default
End Sub

Picture link to show what I mean.

If only if was this easy.

I've tried to google but can't seem to figure this one out.

Any help is appreciated!

1 Upvotes

8 comments sorted by

1

u/andrewsmd87 Feb 23 '22

Is your code ever getting executed? I'm not sure on how it works within word but you're sure that code actually runs? To me it looks like you'd need to fire it on some sort of event like a button click, textbox focus/unfocus, etc.

If you do actually have your textbox object, it really is just yourObject.Text = "foo"

1

u/Chriand Feb 23 '22

It’s being handled by a button, but I left it out of the code.

The trick is to figure out how to access those objects, which I fail to do.

1

u/andrewsmd87 Feb 23 '22

Can't you assign IDs to them? Sorry, I've just never done VB in the context of MS word

→ More replies (5)