问题


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