列表框中的所有文本到MS Word文档

时间:2017-08-26 18:28:14

标签: vb.net ms-word

我正在尝试将列表框中的所有文本传输到MS Word文档中的特定位置,类似于书签。我也试过在书签中做一个样式,但只显示第一行。

我遇到的问题是我需要将ListBox的内容传输到Word文档,并且不知道如何操作。

请尽可能帮助。

这是我的代码。

Imports Word = Microsoft.Office.Interop.Word

Public Class Form1
    #Region "dim"
        Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
        Dim WPath = IO.Path.Combine(exeDir.DirectoryName, "SampleReceipt.doc")
        Dim Word As Word.Application
        Dim Doc As Word.Document
    #End Region

    Private Sub NAR(ByVal o As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
        Catch ex As Exception
            o = Nothing
        Finally

        End Try
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Word = New Word.Application
            Word.Visible = True
            Doc = Word.Documents.Open(WPath)
            Word.ActiveDocument.Bookmarks("txtDate").Select()
            Word.Selection.Text = (TextBox1.Text)
            Word.ActiveDocument.Bookmarks("txtSchoolYear").Select()
            Word.Selection.Text = (TextBox2.Text)
            Word.ActiveDocument.Bookmarks("txtr1").Select()
            Word.Selection.Text = List1.Text
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        List1.Items.Add("string1")
        List1.Items.Add("string2")
        List1.Items.Add("string3")
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

要从ListBox中的项创建字符串,只需使用以下函数

Private Function GetListBoxStrings() As String
    Dim tempString As String = ""
    For Each line As String In List1.Items
        tempString = tempString & line
    Next
    Return tempString
End Function

并使用它如此

Word.ActiveDocument.Bookmarks("txtr1").Select()
Word.Selection.Text = GetListBoxStrings()