我在 MS Word VBA 中創建了 2 個宏,第一個宏用于從下面的指定檔案夾中選擇任何 docx 檔案,如下所示:
Macro 1
Sub test()
Dim intChoice As Integer
Dim strPath As String
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'if the user selects a file
If intChoice <> 0 Then
'get the path selected
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'opens the document
objWord.Documents.Open (strPath)
End If
End Sub
然后我正在處理的第二個字 VBA 宏是我想打開主檔案的地方,即檔案 A,然后呼叫上面的宏打開我從目錄路徑中選擇的檔案 b,以便我可以從檔案中復制內容B 進入本文末尾的檔案 a。
但是,該代碼不起作用,并且在過去 8 小時內一直停留在此問題上,并且在網上的任何地方都找不到正確的組合。第一個宏作業正常,因為我可以選擇任何 docx 檔案并且它成功打開。第二個宏應該打開檔案 a 然后運行第一個宏,它是 call test 并且可以作業。但是代碼不起作用的地方是在我運行呼叫測驗宏之后,沒有發生復制和粘貼,就像我的印象是 selection.whole & selection.copy 一旦我運行打開的呼叫測驗宏就會作業檔案 b 檔案。
所以最后,我想從呼叫測驗宏中打開檔案 b,從檔案 b 中選擇資料以復制到同樣打開的檔案 a 上。
任何幫助都將不勝感激,并且對 vba 一詞并不熟悉,并且第一次這樣做。提前致謝。
Sub test6()
Application.ScreenUpdating = False
Dim strFile As String
strFile = "C:\Users\test\Desktop\tar sheet test\documenta.docx"
If Dir(strFile) <> "" Then
Documents.Open strFile
End If
Call test
Selection.WholeStory
Selection.Copy
Documents("documenta.docx").Activate '
Selection.EndKey wdStory '
Selection.PasteAndFormat wdPasteDefault
End Sub
uj5u.com熱心網友回復:
由于您在 Word 中作業,因此無需創建新Word.Application實體,因為您可以使用現有實體。
我建議您將 sub 轉換test為函式,以便您可以將Document打開的物件test回傳給呼叫 sub 。
我還建議使用Range物件而不是依賴,Selection因為大多數時候它是不必要的。
請嘗試以下代碼:
Sub test6()
Dim strFile As String
strFile = "C:\Users\test\Desktop\tar sheet test\documenta.docx"
Dim destDocument As Document
If Dir(strFile) <> "" Then
Set destDocument = Application.Documents.Open(strFile)
Dim srcDocument As Document
Set srcDocument = test
If Not srcDocument Is Nothing Then
srcDocument.Content.Copy
destDocument.Range(destDocument.Range.End - 1).PasteAndFormat wdPasteDefault
End If
End If
End Sub
Function test() As Document
Dim intChoice As Integer
Dim strPath As String
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'if the user selects a file
If intChoice <> 0 Then
'get the path selected
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
'opens the document
Set test = Application.Documents.Open(strPath)
End If
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338011.html
