Pasting a String from excel to Word using word-VBA

為{幸葍}努か 提交于 2020-08-12 00:48:05

问题


I have my DB in Excel and want to consult it to create reports in Word. I have searched and tried different options but none seem to work. Any suggestions would be of great help. I essentially want to paste the content of the second Message box into the word document.

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:


You can read the documentation, are you using interop?

    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"


来源:https://stackoverflow.com/questions/40855613/pasting-a-string-from-excel-to-word-using-word-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!