VBA:如何统计(读取)细胞?将数据从Excel导出到Word

时间:2015-02-14 09:54:10

标签: excel vba ms-word

我想通过读取(计算)Excel中的单元格将一些数据从Excel导出到Word。我想使用for循环自动读取这些单元格。

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

1 个答案:

答案 0 :(得分:1)

这样做:

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

您只需将n设置为您需要的列数。

或者更好,而不是n=4我会使用类似的东西:

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

它计算第一行中已使用列的确切数量。