简体   繁体   中英

VBA: How to Count(Read) Cells? Exporting Data from Excel to Word

I want to export some data from Excel to Word by reading (counting) the cells inside Excel. I want to use for loop to read those cells automatically.

Sub Macro1()

'initialize variables
'initialize MicrosoftWord App    
Dim wordApp As Word.Application    
'initialize Word document to open new documents   
Dim wordDoc As Word.Document
'create an object to open the Word App
Set wordApp = CreateObject("word.application")
'if the word app is open equal to true
wordApp.Visible = True
'add data in word document
Set wordDoc = wordApp.Documents.Add

'export data from excel to word
'get the location of the data from the excel
'insert new line
wordDoc.Content.InsertAfter (Cells(1, 1)) & vbNewLine
wordDoc.Content.InsertAfter (Cells(1, 2)) & vbNewLine
wordDoc.Content.InsertAfter (Cells(1, 3)) & vbNewLine
wordDoc.Content.InsertAfter (Cells(1, 4))

End Sub

This will do it:

Sub Macro1()

'initialize variables
Dim i As Long, n As Long 'counters
'number of columns in Excel
n = 4
'initialize MicrosoftWord App
Dim wordApp As Word.Application
'initialize Word document to open new documents
Dim wordDoc As Word.Document
'create an object to open the Word App
Set wordApp = CreateObject("word.application")
'if the word app is open equal to true
wordApp.Visible = True
'add data in word document
Set wordDoc = wordApp.Documents.Add

'export data from excel to word
'for every column (beginning 1, ending n)
'   inserting into Word values of cells and a newline
For i = 1 To n
    wordDoc.Content.InsertAfter (Cells(1, i)) & vbNewLine
Next

Set wordDoc = Nothing
Set wordApp = Nothing
End Sub

You just need to set n to the number of columns that you need.

Or better, instead of n=4 I would use something like:

n = Cells(1, Columns.Count).End(xlToLeft).Column

It counts the exact number of used columns in the first row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM