0
我現在使用excel中的宏將一系列單元格導出到Word中。保存從Excel中的範圍導出到Word並保存爲單元格A1的名稱
雖然有一些變化,但我需要它將其複製到新的Word文檔中,而不是腳本中的現有文檔?
我選擇的範圍由各種Vlookup結果組成。
另外,如果可能的話,我想讓文件名是A1中的任何內容。
Sub Export_Table_Data_Word()
'Name of the existing Word document
Const stWordDocument As String = "Table Report.docx"
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdCell As Word.Cell
'Excel objects
Dim wbBook As Workbook
Dim wsSheet As Worksheet
'Count used in a FOR loop to fill the Word table.
Dim lnCountItems As Long
'Variant to hold the data to be exported.
Dim vaData As Variant
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet1")
vaData = wsSheet.Range("A1:A10").Value
'Instantiate Word and open the "Table Reports" document.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordDocument)
lnCountItems = 1
'Place the data from the variant into the table in the Word doc.
For Each wdCell In wdDoc.Tables(1).Columns(1).Cells
wdCell.Range.Text = vaData(lnCountItems, 1)
lnCountItems = lnCountItems + 1
Next wdCell
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
wdApp.Quit
'Null out the variables.
Set wdCell = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
MsgBox "The " & stWordDocument & "'s table has succcessfully " & vbNewLine & _
"been updated!", vbInformation
End Sub
UPDATE:
謝謝尼古拉斯的幫助。下面的最終腳本:
Sub OLDMACROADJUSTED()
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdCell As Word.Cell
'Excel objects
Dim wbBook As Workbook
Dim wsSheet As Worksheet
'Count used in a FOR loop to fill the Word table.
Dim lnCountItems As Long
'Variant to hold the data to be exported.
Dim vaData As Variant
'File path based on A1'
Dim filePath As String
filePath = "C:\FolderName\" & Cells(1, 1).Value & ".doc"
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet1")
vaData = wsSheet.Range("A1:A10").Value
'Instantiate Word and open the new file.
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Add 'Create new app instead of open'
lnCountItems = 1
Dim c As Range
For Each c In Range("B3:B7")
wrdDoc.Content.InsertAfter c
Next c
'Place the data from the variant into the table in the Word doc.
'For Each wdCell In wdDoc.Tables(1).Columns(1).Cells
'wdCell.Range.Text = vaData(lnCountItems, 1)
'lnCountItems = lnCountItems + 1
'Next wdCell
'Save and close the Word doc.
With wrdDoc
If Dir(filePath) <> "" Then
Kill filePath
End If
.SaveAs (Range("B3").Value)
.Close ' close the document
End With
'wdApp.Quit
'Null out the variables.
Set wdCell = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
MsgBox "Your file has been saved in default location of the macro...", vbInformation
End Sub
非常感謝您的答覆。我得到用戶定義的類型未定義的錯誤?然後它突出了昏暗的wdapp部分?我怎樣才能糾正這個@nicholas – user4242750
我也在參考文獻中添加了Word,真的卡在了這裏? @nicholas – user4242750
@ user4242750剛剛更新了wrdApp變量的設置。 – nicholas79171