2016-11-29 215 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)' –