VBA code in word to import excel data

北城余情 提交于 2019-12-08 13:34:51

问题


I have an excel file with data in column A - ZZ, I am needing to import columns E,F,G,I into a table within a word document. I don't want to use mail merge as I want the data all within the same table within word. Can anyone give me any pointers? I have been looking for a while and testing code unsuccessfully.

Sub Macro1()

Dim rowCount2 As Long, shtSrc As Worksheet Dim shtDest As Worksheet Dim rng2 As Range

Set shtSrc = Sheets("Roadmap")
Set shtDest = ActiveDocument.Range(1)

rowCount2 = shtSrc.Cells(Rows.Count, "A").End(xlUp).Row

Set rng2 = shtSrc.Range("A1:A" & rowCount2)


currentRow = 2

For Each cell2 In rng2.Cells
    If cell2.Value <> "" Then
        shtDest.Range("B" & currentRow).Value2 = cell2.Value2
        shtDest.Range("C" & currentRow).Value2 = cell2.Offset(0, 1).Value2
        shtDest.Range("G" & currentRow).Value2 = cell2.Offset(0, 2).Value2
        shtDest.Range("H" & currentRow).Value2 = cell2.Offset(0, 3).Value2
        shtDest.Range("J" & currentRow).Value2 = cell2.Offset(0, 4).Value2
        currentRow = currentRow + 1

    ElseIf cell2.Value = "" Then

    End If
    Next cell2

End Sub


回答1:


Try this code:

Sub test()
Debug.Print ActiveDocument.Range(1).Tables(1).Range.Rows(1).Cells(1).Range
Dim MyExcel As Excel.Application
Dim MyWB As Excel.Workbook
Set MyExcel = New Excel.Application
Set MyWB = MyExcel.Workbooks.Open("C:\Users\marci_000\Documents\Projekty\Almanach\NOTORIA_XLS\AGORA.XLS")

For i = 1 To 6
    ActiveDocument.Range(1).Tables(1).Range.Rows(1).Cells(i).Range = MyWB.Sheets("ConsQRT_Reports").Cells(3, 70 - i)
Next i

MyWB.Close False
Set MyExcel = Nothing
Set MyWB = Nothing
End Sub

I assume that in the first paragraph (ActiveDocument.Range(1)) you have one table (ActiveDocument.Range(1).Tables(1)). The first Debug.print sends to Immediate window the content of the first cell (first row, first column). Then I open an Excel file and for cells (from Excel) 69 down to 64, write contents of row 3 into the cells within the Word table.

After the job is done, Close the file in Excel and do cleaning (=Nothing) - otherwise you will have a bunch of "unfinished" and hidden instances of Excel.



来源:https://stackoverflow.com/questions/29269278/vba-code-in-word-to-import-excel-data

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