Search code examples
excelms-accessvbamovefileex

relocate a dynamic file in VBA


I am trying to have an user select a file and choose a to upload to another location ( like a shared drive). I am using the name function but I realized I am having trouble getting the file name and put into the "toPath" since it is up to the user. Below is my completed code and please any advice or suggestions would help.

At the same time, I hope my codes may help someone is trying to do the samething. Thanks

To Pick a file to upload:

Private Sub Command2_Click()

  Dim fDialog As Variant

    ' Clear listbox contents. '
Me.Path1.Value = ""
' Set up the File Dialog. '
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

With fDialog
   ' Allow user to make multiple selections in dialog box '
  .AllowMultiSelect = False
   ' Set the title of the dialog box. '
  .Title = "Please select one file"
   ' Clear out the current filters, and add our own.'
  .Filters.Clear

  .Filters.Add "All Files", "*.*"
   ' Show the dialog box. If the .Show method returns True, the '
  ' user picked at least one file. If the .Show method returns '
  ' False, the user clicked Cancel. '
  If .Show = True Then
  'add selected path to text box
 Me.Path1.Value = .SelectedItems(1)
   Else
     MsgBox "No File Selected."
  End If
 End With

 End Sub

To Pick a upload path to upload the file:

Private Sub Command10_Click()
Dim FromPath As String
Dim ToPath As String
Dim fDialog2 As Variant
' Clear listbox contents. '
Me.Path2.Value = ""
FromPath = Me.Path1
ToPath = Me.Path2
' Set up the File Dialog. '
Set fDialog2 = Application.FileDialog(msoFileDialogFolderPicker)
With fDialog2

  If .Show = True Then
  'add selected path to text box
 Me.Path2.Value = .SelectedItems(1)
   Else
     MsgBox "No file uploaded."
  End If
  End With

Name FromPath As ToPath & "\" &  'ummmmmmmmmmm I am stucked :(

MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath
End Sub

Solution

  • Refactor the end of Command10_Click as shown below. User can pick new file name.

    ....
    
    End With
    
    Dim ToName as String
    ToName = InputBox("Please Enter New File Name","New File Name")
    
    Name FromPath As ToPath & "\" &  ToName
    
    ....
    

    I am not sure which file types you are relocating, but you can grab the extension type from FromPath and add to end of ToName