2017-01-03 216 views
0

我最近開始嘗試使用vba來自動執行Microsoft Word中的一些日常任務。我正在研究一個代碼,它允許用戶選擇一個目標文件夾以及要複製到所選目標文件夾的文件(.doc)。使用vba複製粘貼微軟word文件到另一個文件夾

以下代碼運行時沒有錯誤,但是文件不會將複製粘貼到目標文件夾中。

我將非常感謝任何幫助來解決這個分鐘的問題。

問候,

德里克

Sub copydocs() 

Dim items As Long 
Dim file_path As Variant 
Dim folder_path As Variant 

    'Ask user for input' 

    items = InputBox("Give me some input") 


    'Select Destination Folder 
    With Application.FileDialog(msoFileDialogFolderPicker) 
     folder_path = .SelectedItems(1) 
     .Show 
    End With 


    ' Open the file dialog 
    For i = 1 To items 
     With Application.FileDialog(msoFileDialogFilePicker) 
      .AllowMultiSelect = True 
      .Show 
      file_path = .SelectedItems(1) 
     End With 

     ' Copy paste  
     Dim fs As Object 
     Set fs = CreateObject("Scripting.FileSystemObject") 
     fs.CopyFile file_path, folder_path 
     Set fs = Nothing 

    Next i  

End Sub 

回答

0

有幾個問題。

變量i沒有在任何地方聲明。

您正試圖在對話返回之前保存文件夾路徑。

Sub copydocs() 
    Dim i As Integer    ' CHANGE: New declare. 
    Dim fs As Object    ' CHANGE: Moved to top. 
    Dim items As Long 
    Dim file_path As Variant 
    Dim folder_path As Variant 

    'Ask user for input. 
    items = InputBox("Give me some input") 

    'Select Destination Folder 
    With Application.FileDialog(msoFileDialogFolderPicker) 
     ' CHANGE: Switched order of next two lines. 
     .Show 
     folder_path = .SelectedItems(1) 
    End With 

    ' Open the file dialog 
    For i = 1 To items 
     With Application.FileDialog(msoFileDialogFilePicker) 
      .AllowMultiSelect = True 
      .Show 
      file_path = .SelectedItems(1) 
     End With 

     ' Copy paste 
     Set fs = CreateObject("Scripting.FileSystemObject") 
     fs.CopyFile file_path, folder_path 
     Set fs = Nothing 
    Next i 
End Sub 
相關問題