2017-08-24 214 views
0

我試圖使用Excel工作表中的信息自動填充Word文檔。我希望用戶能夠選擇所需的excel文件,並希望我的宏從excel文件的不同頁面複製特定範圍,並將其粘貼到word中的特定區域。到目前爲止,我可以打開我選擇的excel文件,但不知道如何選擇範圍並粘貼到特定位置。此外,我正在使用單詞VBA做所有這些工作,並且還希望使用單詞VBA複製粘貼excel範圍。我試圖從名爲Main的表格複製單元格C25,並從名爲summary的表格中將表格A5複製到C28。單元格C25是一個名字,所以我想把它放在一個單詞文檔中,在行後請註明親愛的名字和張貼表,請看下面的摘要:。這是我迄今爲止所能夠選擇的excel文件並打開它。如何從工作表中複製excel範圍,並將其放入特定位置,然後將其放入使用word vba的特定位置中的文字

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 

回答

0

這看起來像馬拉松第一英里後的疲憊雙腿:-)。你將不得不在開始的道路上繼續前進。但是不要將所有內容都聲明爲Object。 xlApp是一個Excel.Application。 xlBook是一個Excel.Workbook。 MyDoc是一個Word.Document,但您在運行Word代碼時無需指定Word。

但是,您必須設置MyDoc,例如Set MyDoc = ActiveDocument。 聲明Dim Ws As Excel.WorksheetSet 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文檔的具體問題。我試圖在這裏指出的一點是,在你遇到任何無法用疲倦解釋的問題之前,你的項目中會有很多細緻的工作要做。保持良好的工作,男人。還有祝你好運! (請儘量避免任何看起來像後續問題的東西,哈哈:)

相關問題