[英]How to copy excel range from a sheet and place it into a specific place it into a specific place in word using word vba
我正在嘗試使用 Excel 工作表中的信息自動填充 Word 文檔。 我希望用戶能夠選擇所需的 excel 文件,並希望我的宏從 excel 文件的不同工作表中復制特定范圍並將其粘貼到 word 中的特定區域。 到目前為止,我能夠打開我選擇的 excel 文件,但不確定范圍選擇和粘貼到特定位置的工作方式。 另外,我正在使用 word VBA 完成所有這些操作,並且還想使用 word VBA 來復制粘貼 excel 范圍。 我試圖從名為 Main 的工作表中復制單元格 C25,並從名為 summary 的工作表中復制范圍為 A5 到 C28 的表。 單元格 C25 是一個名稱,所以我想將它放在一個 word 文檔中,說明親愛的姓名,並在該行之后發布表格,請參閱下面的摘要:.這是我迄今為止所擁有的,可以讓我選擇 excel 文件並打開它。
Sub Macro1_FileOpen()
'
' Macro1_FileOpen Macro
'
'
'Dim FilePath As Object
'Dim dSource As String
'With Me.Application.FileDialog(Microsoft.Office.Core.MsoFileDialogType.msoFileDialogOpen)
' .AllowMultiSelect = True
'.Filters.Clear
'.Filters.Add "Excel Files", "*.xls;*.xlw"
' .Filters.Add "All Files", "*.*"
' If .Show = True Then
' .Execute()
'End If
'End With
Dim xlApp As Object
Dim xlBook As Object
Dim dSource As String
Dim ExcelWasNotRunning As Boolean
Dim MyDOc As Word.Document
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Title = "Select the file that you wish to use."
.InitialFileName = strFolder
.Filters.Clear
.Filters.Add "Excel Files", "*.xls?"
.AllowMultiSelect = False
If .Show = -1 Then
dSource = .SelectedItems(1)
Else
MsgBox "You cancelled the operation"
Exit Sub
End If
End With
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
With xlApp
Set xlBook = .Workbooks.Open(dSource)
MsgBox "The workbook" & vbCr & dSource & vbCr & "is open!"
'Insert code to do what you need to do with the workbook here
Set xlBook = Nothing
End With
If ExcelWasNotRunning Then
xlApp.Quit
End If
Set xlBook = Nothing
Set xlApp = Nothing
Set fd = Nothing
End Sub
這看起來像是馬拉松第一英里后腿疲倦的情況:-)。 你只需要在你開始的方式上繼續前進。 但要避免將所有內容都聲明為 Object。 xlApp 是一個 Excel.Application。 xlBook 是一個 Excel.Workbook。 MyDoc 是一個 Word.Document,但在從 Word 運行代碼時不需要指定 Word。
但是,您必須設置 MyDoc,例如Set MyDoc = ActiveDocument
。 將Dim Ws As Excel.Worksheet
聲明Dim Ws As Excel.Worksheet
並Set Ws = xlBook.Worksheets("Main")
您將需要一個字符串來從 xlBook 中獲取文本。 所以Dim Tmp As String
。 然后你可以說Tmp = Ws.Cells(25, "C").Value
,在 MyDoc 中查找位置並將其插入那里。
然后你可以聲明Dim Tbl As Table
和
Set Ws = xlBook.Worksheets("Summary")
With Ws
Set Tbl = .Range(.Cells(5, "A"), .Cells(28, "C"))
End With
實際上,我絕不確定這會起作用 - 將 Excel 范圍分配給 Word 表 - 但如果它不起作用,您可以嘗試簡單地將 Excel.Range 直接復制到您的 Word 文檔中,或者嘗試在您使用時記錄這些步驟執行它們,或在此處詢問有關如何將 Excel 范圍復制到 Word 文檔的特定問題。 我想在這里說明的一點很簡單,在您遇到任何無法用疲倦來解釋的問題之前,您的項目還有很多細節工作要做。 繼續努力,伙計。 祝你好運! (請盡量避免任何看起來像后續問題的內容,哈哈:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.