本文介绍了使用 word-VBA 将字符串从 excel 粘贴到 Word的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

推荐答案

你可以阅读文档,你在使用互操作吗?

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"

这篇关于使用 word-VBA 将字符串从 excel 粘贴到 Word的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:53