2016-11-29 115 views
0

我在Excel中有我的数据库,并且希望咨询它以在Word中创建报告。我搜索并尝试了不同的选项,但似乎没有任何工作。任何建议都会有很大的帮助。我基本上想要将第二个消息框的内容粘贴到Word文档中。使用word-VBA粘贴字符串从excel到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" 
+0

你想在Word文档中放置内容的位置?一个好的方法可能是在你的word文件中创建可以放置内容的书签。如果不了解更多关于你想在Word中创建什么内容,那么就如何采取最好的方法提出有用的建议很困难。 –

+0

现在我想把它粘贴到文档的末尾,我可以使用书签,但如果我是正确的,他们需要预先定义,我的报告不会总是有相同数量的书签,但我会试一试。 – MrPapity

+0

你打算在哪里运行这段代码 - 你不需要为Word *和* Excel都使用CreateObject()... –

回答

0

您可以阅读文档,是否使用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" 
+0

我试图在不断遇到的问题 objWord.Documents.addParagraph() 或任何变化是它给我一个“运行时错误'438':对象不支持此属性或方法” – MrPapity

+0

'objWord。文档“是指在Word上打开的文档的集合 - 尝试'objWord.Documents(1)' –