Monday, November 16, 2009

Word: Copying a Range of Cells from Excel into Word

'----------------------------------------------------------------------
' Copying a Range of Cells from Excel into Word
'----------------------------------------------------------------------
Sub CopyXLRangeIntoWord()

Dim strData As String
Dim lngChannel As Long
Dim r As Range
Dim str As String
Dim strFilePath As String
Dim strFileName As String

str = "R1C1: R21C7" 'Specify the Excel range you want to copy
strFilePath = "C:\temp\test.xls"
strFileName = "test.xls"

'Open a dynamic data exchange (DDE) channel to Excel Application
lngChannel = DDEInitiate(App:="Excel", Topic:="System")

'Send OPEN command to Excel through initiated channel
DDEExecute Channel:=lngChannel, Command:="[OPEN(" & Chr(34) _
& strFilePath & Chr(34) & ")]"

'Send COPY command to Excel through initiated channel
DDEExecute Channel:=lngChannel, Command:="[COPY(" & Chr(34) _
& "R1C1:R21C7" & Chr(34) & ")]"

'Close the DDE channel to Excel
DDETerminate Channel:=lngChannel

lngChannel = DDEInitiate(App:="Excel", Topic:=strFileName)

'Request information from Excel
strData = DDERequest(Channel:=lngChannel, Item:=str)
'Terminate all channels to Excel
DDETerminateAll

'Paste Excel range into Word Document
'To Paste as text in the beginning of Word document:
ActiveDocument.Range.InsertBefore strData
' To Paste as Picture in the beginning of Word Document:
'ActiveDocument.Range(End:=0).PasteSpecial DataType:=wdPasteEnhancedMetafile

End Sub

1 comment:

  1. A really useful code for copying a range of cells of an excel file to a Word file.Moreover as its presented with a detailed documentation so it also helped me to understand how it functions.Thanks man for such a great post.
    digital signature certificate

    ReplyDelete