使用word-VBA将字符串从excel粘贴到Word

时间:2016-11-29 00:00:00

标签: string vba object word-vba

我在Excel中有我的数据库,想要查阅它以在Word中创建报告。我搜索并尝试了不同的选项,但似乎没有工作。任何建议都会有很大帮助。我本质上想将第二个消息框的内容粘贴到word文档中。

Dim ctl As Control  
Dim some As String
Dim objExcel As Object
Dim objWord As Object
On Error Resume Next

    Set objExcel = GetObject(, "Excel.Application")
    If objExcel Is Nothing Then
        Set objExcel = CreateObject("Excel.Application")
    End If

    Set objWord = GetObject(, "Word.Application")
    If objWord Is Nothing Then
        Set objWord = CreateObject("Word.Application")
    End If

    On Error GoTo 0

    objExcel.Workbooks.Open ("File_Dir")
    objExcel.Visible = False
    objWord.Documents.Open ("File_Dir")
    objWord.Visible = True

    For Each ctl In Me.Controls
         Select Case TypeName(ctl)
             Case "CheckBox"
                 If ctl.Value = True Then
                     MsgBox ctl.Name
                     MsgBox objExcel.Names(ctl.Name).RefersToRange.Value
                     some = objExcel.Names(ctl.Name).RefersToRange.Value

                 End If
         End Select
        Next ctl
    objExcel.Quit
    Set objExcel = Nothing
    MsgBox "complete"

1 个答案:

答案 0 :(得分:0)

您可以阅读文档吗,您使用的是互操作吗?

    Dim ctl As Control  
    Dim some As String
    Dim objExcel As Object
    Dim objWord As Object
    On Error Resume Next

    Set objExcel = GetObject(, "Excel.Application")
    If objExcel Is Nothing Then
            Set objExcel = CreateObject("Excel.Application")
    End If

    Set objWord = GetObject(, "Word.Application")
    If objWord Is Nothing Then
            Set objWord = CreateObject("Word.Application")
    End If

    On Error GoTo 0

    objExcel.Workbooks.Open ("File_Dir")
    objExcel.Visible = False
    objWord.Documents.Open ("File_Dir")
    objWord.Visible = True

    'give a counter for paragraph
    Dim ctr as Integer = 1

    For Each ctl In Me.Controls
        Select Case TypeName(ctl)
            Case "CheckBox"
                If ctl.Value = True Then
                     MsgBox ctl.Name
                     some = objExcel.Names(ctl.Name).RefersToRange.Value
                     MsgBox some

                     'You can write data to Word document here
                     'You must add paragraph
                     objWord.Documents.addParagraph()
                     objWord.Documents.Paragraph(ctr).Range(ctl.Name)
                     ctr = ctr + 1

                End If
        End Select
    Next ctl
    objExcel.Quit
    Set objExcel = Nothing
    MsgBox "complete"