首页 > 解决方案 > VB 2019 使用书签向 MS Word 发送数据

问题描述

我创建了一个程序,允许用户将数据输入到文本框中,然后单击一个按钮将该数据发送到 Word 文档模板。我正在使用书签来指定数据显示的位置。除了一件事,一切都有效。在打开初始文档并且文本填充了第一组书签后,当我返回程序并更改一些文本并再次单击按钮时,它会打开一个新文档并显示该文件正在使用中,就是这样。我想继续添加到打开的文档中。我有 42 个书签,但我只能填充前 4 个。关于如何继续向同一个文档添加文本直到所有 42 个书签都有数据的任何想法?电缆贴标机图片

Imports Word = Microsoft.Office.Interop.Word
Public Class MainForm
Private Sub CreateLabelButton_Click(sender As Object, e As EventArgs) Handles CreateLabelButton.Click
        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.Open("C:\Users\r101931\Documents\Cable Label Automator\Cable Label Automator\bin\Debug\net5.0-windows\CableLabelFormx.docx")

    'Start Adding text from the form to the document template
    If oDoc.Bookmarks.Item("BookMark1").Empty = True And oDoc.Bookmarks.Item("BookMark2").Empty = True And oDoc.Bookmarks.Item("BookMark4").Empty = True And oDoc.Bookmarks.Item("BookMark4").Empty = True Then
        oDoc.Bookmarks.Item("BookMark1").Range.Text = AggPPLabel.Text
        oDoc.Bookmarks.Item("BookMark2").Range.Text = AggSwitchNameLabel.Text
        oDoc.Bookmarks.Item("BookMark3").Range.Text = ServerPPLabel.Text
        oDoc.Bookmarks.Item("BookMark4").Range.Text = ServerServerRackLabel.Text

    ElseIf oDoc.Bookmarks.Item("BookMark5").Empty = True And oDoc.Bookmarks.Item("BookMark6").Empty = True And oDoc.Bookmarks.Item("BookMark7").Empty = True And oDoc.Bookmarks.Item("BookMark8").Empty = True Then
        oDoc.Bookmarks.Item("BookMark5").Range.Text = AggPPLabel.Text
        oDoc.Bookmarks.Item("BookMark6").Range.Text = AggSwitchNameLabel.Text
        oDoc.Bookmarks.Item("BookMark7").Range.Text = ServerPPLabel.Text
        oDoc.Bookmarks.Item("BookMark8").Range.Text = ServerServerRackLabel.Text
End If

End Sub

'All 6 textboxes use the same code to update the labels

Private Sub DeviceNameTextbox_Click(sender As Object, e As EventArgs) Handles DeviceNameTextbox.Click
    'Populate labels if textbox is clicked
    AggPPLabel.Text = AggRackPPPortTextbox.Text & Environment.NewLine & SwitchTypeTextbox.Text & Environment.NewLine & SwitchNamePortTextbox.Text
    AggSwitchNameLabel.Text = SwitchTypeTextbox.Text & Environment.NewLine & SwitchNamePortTextbox.Text & Environment.NewLine & AggRackPPPortTextbox.Text
    ServerPPLabel.Text = RackPPPortTextbox.Text & Environment.NewLine & DeviceNameTextbox.Text & Environment.NewLine & DeviceNamePortTextbox.Text
    ServerServerRackLabel.Text = DeviceNameTextbox.Text & Environment.NewLine & DeviceNamePortTextbox.Text & Environment.NewLine & RackPPPortTextbox.Text
End Sub
End Class

标签: vb.netms-wordvisual-studio-2019bookmarks

解决方案


推荐阅读