Daniel Strong
Daniel Strong

Reputation: 213

Importing excel data

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

Upvotes: 0

Views: 12617

Answers (1)

Marcin Nowicki
Marcin Nowicki

Reputation: 46

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.

Upvotes: 3

Related Questions