[英]How to get content from MS word cells with VBA and clean it for Excel
[英]VBA: How to Count(Read) Cells? Exporting Data from Excel to 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
這樣做:
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
它計算第一行中已使用列的確切數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.