VBA复制并重命名用户在对话框中选择的文件

时间:2017-05-22 10:35:53

标签: vba userform

我需要这个VBA宏,让用户从他们自己的文件夹中选择一个PDF文件,然后宏应该将PDF复制到固定的文件夹目的地,并根据在ComboBoxes中选择的两个值重命名该文件。

我已尝试过以下代码,但在最后一句中失败了。谁能帮帮我?

Sub add_testrepport()
   Dim intChoice As Integer
   Dim strPath As String

   'allow the user to select one file
   Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

   'make the file dialog visible to the user
   intChoice = Application.FileDialog(msoFileDialogOpen).Show

   'determine what choice the user made
   If intChoice <> 0 Then

      'get the file path selected by the user
       strPath = Application.FileDialog( _
         msoFileDialogOpen).SelectedItems(1)

      'copy the file path to filecopy
      FileCopy strPath, "K:\05_RAP\Klement\Test"
   End If
End Sub

2 个答案:

答案 0 :(得分:0)

好的,所以你想要的步骤是:

如果您遇到任何代码的任何特定问题,请相应更新您的问题以获得具体答案。

答案 1 :(得分:0)

这有点旧,但如果您仍在寻找答案,那么从msoFileDialogOpen前面移除下划线和空格一样简单吗?当我复制并粘贴到Excel中时,它最初不会编译;但在纠正之后,它运行良好。也就是说,它复制了一个文件,在我创建的Test文件夹中命名为K:\05_RAP\Klement\(无扩展名)。

如果您打算将Test作为具有文件原始文件名的文件夹,您可以尝试使用此代码(将2行留空,然后缩进4个空格以在StackOverflow中发布代码):

Sub add_testrepport()

Dim intChoice As Integer
Dim strPath As String
Dim strFName As String

'allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show

'determine what choice the user made
If intChoice <> 0 Then

    'get the file path selected by the user
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

    ' get file name from path
    strFName = Mid(strPath, InStrRev(strPath, "\") + 1, Len(strPath))

    'copy the file path to filecopy
    FileCopy strPath, "K:\05_RAP\Klement\Test\" & strFName

End If

End Sub