to move files from one folder to another using VBA - excel

I have a code which can transfer the Excel files from one folder to another but i would like to update the code so that it can move all the files (.xml, .txt, .pdf, etc.) from one folder to another.
Sub MoveFiles()
Dim sourceFolderPath As String, destinationFolderPath As String
Dim FSO As Object, sourceFolder As Object, file As Object
Dim fileName As String, sourceFilePath As String, destinationFilePath As String
Application.ScreenUpdating = False
sourceFolderPath = "E:\Source"
destinationFolderPath = "E:\Destination"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.GetFolder(sourceFolderPath)
For Each file In sourceFolder.Files
fileName = file.Name
If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved
sourceFilePath = file.Path
destinationFilePath = destinationFolderPath & "\" & fileName
FSO.MoveFile Source:=sourceFilePath, Destination:=destinationFilePath
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be moved
Next
'Don't need set file to nothing because it is initialized in for each loop
'and after this loop is automatically set to Nothing
Set sourceFolder = Nothing
Set FSO = Nothing
End Sub
can you please help

Move Files Using MoveFile
You would get greater control of things by using CopyFile and DeleteFile instead of MoveFile.
Using Dir, FileCopy, and Kill, instead of the FileSystemObject object and its methods, would make it simpler and also faster.
Option Explicit
Sub MoveFilesTEST()
Const sFolderPath As String = "E:\Source"
Const dFolderPath As String = "E:\Destination"
Const FilePattern As String = "*.*"
MoveFiles sFolderPath, dFolderPath, FilePattern
End Sub
Sub MoveFiles( _
ByVal SourceFolderPath As String, _
ByVal DestinationFolderPath As String, _
Optional ByVal FilePattern As String = "*.*")
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(SourceFolderPath) Then
MsgBox "The source folder path '" & SourceFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
If Not fso.FolderExists(DestinationFolderPath) Then
MsgBox "The destination folder path '" & DestinationFolderPath _
& "' doesn't exist.", vbCritical
Exit Sub
End If
Dim apSep As String: apSep = Application.PathSeparator
Dim sPath As String: sPath = SourceFolderPath
If Left(sPath, 1) <> apSep Then sPath = sPath & apSep
Dim sFolder As Object: Set sFolder = fso.GetFolder(sPath)
If sFolder.Files.Count = 0 Then
MsgBox "There are no files in the source folder '" & sPath & "'.", _
vbExclamation
Exit Sub
End If
Dim dPath As String: dPath = DestinationFolderPath
If Left(dPath, 1) <> apSep Then dPath = dPath & apSep
Dim dFolder As Object: Set dFolder = fso.GetFolder(dPath)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim sFile As Object
Dim dFilePath As String
Dim ErrNum As Long
Dim MovedCount As Long
Dim NotMovedCount As Long
For Each sFile In sFolder.Files
dFilePath = dPath & sFile.Name
If fso.FileExists(dFilePath) Then
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
Else
On Error Resume Next
fso.MoveFile sFile.Path, dFilePath
ErrNum = Err.Number
' e.g. 'Run-time error '70': Permission denied' e.g.
' when the file is open in Excel
On Error GoTo 0
If ErrNum = 0 Then
MovedCount = MovedCount + 1
Else
dict(sFile.Path) = Empty
NotMovedCount = NotMovedCount + 1
End If
End If
Next sFile
Dim Msg As String
Msg = "Files moved: " & MovedCount & "(" & NotMovedCount + MovedCount & ")"
If NotMovedCount > 0 Then
Msg = Msg & vbLf & "Files not moved:" & NotMovedCount & "(" _
& NotMovedCount + MovedCount & ")" & vbLf & vbLf _
& "The following files were not moved:" & vbLf _
& Join(dict.keys, vbLf)
End If
MsgBox Msg, IIf(NotMovedCount = 0, vbInformation, vbCritical)
End Sub

Related

Move files from multiple folders to a single folder

I am trying to consolidate Excel files from different folders to a single folder. Within each folder there is a single Excel file.
Sub move_data()
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim Fdate As Date
Dim FileInFromFolder As Object
MkDir "C:\User\TEST\"
FromPath = "C:\User\MainFolder\"
ToPath = "C:\User\TEST\"
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
For Each FileInFromFolder In FSO.GetFolder(FromPath).Files
FileInFromFolder.Move ToPath
Next FileInFromFolder
End Sub
The code is unable to get the files from the subfolder within the folder (as shown in the image).
The area I am looking to change is 'FromPath', if it is possible to include a wildcard to specify the subfolders?
Multiple Folders, One Excel file per Folder
Move Files From Multiple Folders to Single Folder (FileSystemObject)
Sub MoveFiles()
Const FromPath As String = "C:\MainFolder\"
Const ToPath As String = "C:\Test\"
Const LCaseExtensionPattern As String = "xls*"
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(FromPath) Then
MsgBox "The folder '" & FromPath & "' doesn't exist.", vbCritical
Exit Sub
End If
If Not fso.FolderExists(ToPath) Then MkDir ToPath
Dim SubFolderPaths() As String: SubFolderPaths = ArrSubFolderPaths(FromPath)
Dim fsoFile As Object
Dim NotMoved() As String
Dim n As Long
Dim mCount As Long
Dim nmCount As Long
For n = 0 To UBound(SubFolderPaths)
For Each fsoFile In fso.GetFolder(SubFolderPaths(n)).Files
If LCase(fso.GetExtensionName(fsoFile)) _
Like LCaseExtensionPattern Then
If Not fso.FileExists(ToPath & fsoFile.Name) Then
mCount = mCount + 1
fsoFile.Move ToPath
Else
nmCount = nmCount + 1
ReDim Preserve NotMoved(1 To nmCount)
NotMoved(nmCount) = fsoFile.Path
End If
End If
Next fsoFile
Next n
Dim MsgString As String
MsgString = "Files moved: " & mCount & "(" & mCount + nmCount & ")"
If nmCount > 0 Then
MsgString = MsgString & vbLf & vbLf & "Files not moved: " & mCount _
& "(" & mCount + nmCount & "):" & vbLf & vbLf & Join(NotMoved, vbLf)
End If
MsgBox MsgString, vbInformation
End Sub
Function ArrSubFolderPaths( _
ByVal InitialFolderPath As String, _
Optional ByVal ExcludeInitialFolderPath As Boolean = False) _
As String()
Const ProcName As String = "ArrSubFolderPaths"
On Error GoTo ClearError
' Ensure that a string array is passed if an error occurs.
Dim Arr() As String: Arr = Split("") ' LB = 0 , UB = -1
' Locate the trailing path separator.
Dim pSep As String: pSep = Application.PathSeparator
If Right(InitialFolderPath, 1) <> pSep Then
InitialFolderPath = InitialFolderPath & pSep
End If
' Add the initial folder path to a new collection.
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim coll As Collection: Set coll = New Collection
coll.Add fso.GetFolder(InitialFolderPath)
' Add the initial folder path (or don't) to the result.
Dim n As Long
If ExcludeInitialFolderPath Then ' don't add
n = -1
Else ' add
ReDim Preserve Arr(0 To 0): Arr(0) = coll(1)
End If
Dim fsoFolder As Object
Dim fsoSubFolder As Object
Do While coll.Count > 0
Set fsoFolder = coll(1)
coll.Remove 1
For Each fsoSubFolder In fsoFolder.SubFolders
coll.Add fsoSubFolder
n = n + 1: ReDim Preserve Arr(0 To n): Arr(n) = fsoSubFolder
Next fsoSubFolder
Loop
ArrSubFolderPaths = Arr
ProcExit:
Exit Function
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Function
This is simple to achieve if you adopt recursive procedure.
Sub Starter()
Call FilesMover("C:\User\MainFolder\", "C:\User\TEST\")
End Sub
Sub FilesMover(FromPath As String, DestinationPath As String)
Dim fso As object
Set fso = CreateObject("scripting.filesystemobject")
Dim f As File
Dim d As Folder
' first move the files in the folder
For Each f In fso.GetFolder(FromPath).Files
f.Move DestinationPath
Next f
' then check the subfolders
For Each d In fso.GetFolder(FromPath).SubFolders
Call FilesMover(d.Path, DestinationPath)
Next d
End Sub

Search a folder for keyword - FINDSTR Still does not work [duplicate]

I'm trying to use Excel VBA to find a string in a folder, but it seems the FINDSTR command line is not working.
I'm wondering if it could be a change in Windows (I'm using Win10), or if I don't have a have the correct "Reference" selected (I do have the Microsoft Scripting Runtime selected).
Sub ListFilesContainingString()
Dim myfile As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
wrd = InputBox("Word:", "Insert search word")
If wrd = "" Then
MsgBox "???"
Exit Sub
End If
myfile = FindFiles(GetFolder, wrd)
If (myfile <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
I fixed the typo but FINDSTR is still not working correctly. My current code is below. Note that there are several instances of FINDSTR and FIND so I can see what is being returned (the "If, Then x=x" code is only to place a breakpoint). FINDSTR returns "", FIND returns a file but it isn't a correct file.
FINDSTR does work using a dos/powershell window.
Sub ListFilesContainingString()
'this macro finds vendor information on the chosen file for each part in the origin file
Dim myfile As String
Dim fldr As FileDialog
Dim sItem As String
Dim wrd As String
''''''''''''''''''''''''''''''''''''''
Dim objFSO As Object
Dim objFolders As Object
Dim objFolder As Object
Dim DirFolderRename As String
Dim arrFolders() As String
Dim FolderCount As Long
Dim FolderIndex As Long
''''''''''''''''''''''''''''''''''''''
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
''''''''''''''''''''''''''''''''''''''
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolders = objFSO.GetFolder(sItem).SubFolders
FolderCount = objFolders.Count
If FolderCount > 0 Then
ReDim arrFolders(1 To FolderCount)
FolderIndex = 0
For Each objFolder In objFolders
FolderIndex = FolderIndex + 1
arrFolders(FolderIndex) = objFolder.Name
Next objFolder
Else
MsgBox "No folders found!", vbExclamation
End If
Set objFSO = Nothing
Set objFolders = Nothing
Set objFolder = Nothing
''''''''''''''''''''''''''''''''''''''
Set wrdAddr = Application.InputBox("Select First Word to Search For", "Obtain Range Object", Type:=8)
wrdCol = wrdAddr.Column
wrdRow = wrdAddr.Row
StartCell = Cells(wrdRow, wrdCol).Address
Range(StartCell).Activate
wrd = ActiveCell.Value
While (wrd <> "")
'wrd = InputBox("Word:", "Insert search word")
If wrd = "" Then
MsgBox "???"
Exit Sub
End If
For i = 1 To FolderCount
TheFolder = GetFolder & "\" & arrFolders(i)
myfile = FindFiles(TheFolder, wrd)
If (myfile <> "") Then
ActiveCell.Offset(0, 17).Value = ActiveCell.Offset(0, 17).Value & arrFolders(i) & ","
End If
Next i
ActiveCell.Offset(1, 0).Select
wrd = ActiveCell.Value
Wend
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files1, files2, files3, files4 As String
Dim lines
'''' This works in the dos window
' findstr /M /S /I L298P C:\Users\Wm" "Boyd\Documents\Boyd" "Manufacturing\Customers\Inactive\*.xls?
''''
exec ("FINDSTR /M L298P C:\Users\Wm""Boyd\Documents\Boyd""Manufacturing\Customers\Inactive\*.xls?")
files1 = CreateObject("WScript.Shell").exec("FINDSTR /M """ & target & """ """ & path & "\*.xls?""").StdOut.Read
files2 = CreateObject("Wscript.Shell").exec("FINDSTR /M L298P C:\Users\Wm""Boyd\Documents\Boyd""Manufacturing\Customers\Inactive\*.xlsx").StdOut.ReadAll
If files1 <> "" Then
x = x
End If
files3 = CreateObject("Wscript.Shell").exec("FIND """ & target & """ """ & path & "\*.xls?""").StdOut.ReadAll
files4 = CreateObject("Wscript.Shell").exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
lines = Split(files1, vbCrLf)
Dim curFile As String
Dim line
For Each line In lines
If (Left(line, 11) = "---------- ") Then
curFile = Mid(line, 12)
End If
If (curFile <> "") Then
FindFiles = curFile
Exit Function
End If
Next
'files = CreateObject("Wscript.Shell").Exec("FINDSTR """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
'If (files <> "") Then
'Dim idx As Integer
'idx = InStr(files, vbCrLf)
'FindFiles = Left(files, idx - 1)
'End If
FindFiles = ""
End Function
I have created a log file to record the command executed and the response. This is a first step, if it works the next step would be to parse the response for the information you want.
Option Explicit
Sub ListFilesContainingString()
Const qq = """"
' get first word from sheet
Dim wrdCell As Range
Set wrdCell = Application.InputBox("Select First Word to Search For", _
"Obtain Range Object", Type:=8)
If Len(wrdCell.Value2) = 0 Then
MsgBox "No word selected", vbCritical
Exit Sub
End If
' start logging
Dim Folder As String, FSO As Object, tsLog As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim logfile As String, cmd As String, n As Long
Dim msg As String, W As Object, s As String
logfile = ThisWorkbook.path & "\" & "Log_" _
& Format(Now(), "yyyymmdd_hhmmss") & ".txt"
Set tsLog = FSO.CreateTextFile(logfile)
Set W = CreateObject("Wscript.Shell")
' get folders
Folder = GetFolder("C:\") 'start in c:\
If Len(Folder) = 0 Then Exit Sub
' scan for each words
Do While Not IsEmpty(wrdCell)
' message box
msg = msg & vbLf & wrdCell.Address & " " & wrdCell
' build command
s = qq & wrdCell & qq & " " & qq & Folder
cmd = "FINDSTR /M /S " & s & "\*.*" & qq
tsLog.writeLine "Command" & vbCrLf & cmd & vbCrLf
' execute
s = W.exec(cmd).StdOut.ReadAll
tsLog.writeLine "Result" & vbCrLf & ">" & s & "<" & vbLf
' next
n = n + 1
Set wrdCell = wrdCell.Offset(1)
Loop
tsLog.Close
MsgBox "Words searched for " & msg, vbInformation, "See " & logfile
Shell "notepad.exe " & logfile
End Sub
Function GetFolder(strPath) As String
Dim fldr As FileDialog
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then
MsgBox "Cancelled", vbExclamation
Exit Function
End If
GetFolder = .SelectedItems(1)
End With
End Function

Loop through files in a given folder, check cell content in CLOSED files to identify template and add said files to array

I'm mainly trying to work off of the solution in this thread How to loop through all sheets in all workbooks within a folder.
This is the code responsible for filling the array
'Fill the array(myFiles)with the list of Excel files in the folder
Fnum = 0
Do While FilesInPath <> ""
Fnum = Fnum + 1
ReDim Preserve MyFiles(1 To Fnum)
MyFiles(Fnum) = FilesInPath
FilesInPath = Dir()
Loop
If I understand it correctly, it should loop through all files in a given folder and retrieve every excel file in it.
Based on this thread ExecuteExcel4Macro to get value from closed workbook ExecuteExcel4Macro(string) should allow to check/retrieve the content of a given cell in a closed workbook of which I already have its name and its sheet's name.
I want to check the value of a cell (so I can identify whether the file is based on a template which I would like to work on) so it gets added to the array in the first.
I would like to integrate the solution to check cell content into the loop I pasted above.
Option Explicit
Sub Sample()
Dim wbPath As String, wbName As String
Dim wsName As String, cellRef As String
Dim Ret As String
'wbPath = "C:\Documents and Settings\Siddharth Rout\Desktop\"
wbPath = "C:\Users\my.name\Desktop\"
wbName = "QOS DGL stuff.xls"
wsName = "ACL"
cellRef = "C3"
Ret = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, -4150)
MsgBox ExecuteExcel4Macro(Ret)
End Sub
Check Cell in Closed Files (ExecuteExcel4Macro)
Option Explicit
Sub ProcessFiles()
Dim sFolderPath As String
sFolderPath = Environ("USERPROFILE") & "\OneDrive\Documents\Test\"
Const sExtensionPattern As String = "*.xls*"
Const swsName As String = "ACL"
Const sCellAddress As String = "C3"
Const sString As String = "Yes"
Dim sFileName As String: sFileName = Dir(sFolderPath & sExtensionPattern)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim cString As String
Do While Len(sFileName) > 0
cString = GetCellString(sFolderPath, sFileName, swsName, sCellAddress)
If StrComp(cString, sString, vbTextCompare) = 0 Then
' You could process the files here without writing them
' to a data structure...
dict(sFolderPath & sFileName) = Empty
End If
sFileName = Dir
Loop
If dict.Count = 0 Then Exit Sub
Debug.Print Join(dict.Keys, vbLf)
' ' ... or loop through the dictionary ...
' Dim Key As Variant
' For Each Key In dict.Keys
' ' Continue
' 'Debug.Print Key
'
' Next Key
'
' ' ... or write the values from the dictionary to an array
' ' and loop through the array.
' Dim MyFiles As Variant: MyFiles = dict.Keys
'
' Dim n As Long
'
' For n = 0 To UBound(MyFiles)
' ' Continue
' 'Debug.Print MyFiles(n)
' Next n
End Sub
Function GetCellString( _
ByVal wbPath As String, _
ByVal wbName As String, _
ByVal wsName As String, _
ByVal CellAddress As String) _
As String
Const ProcName As String = "GetCellString"
On Error GoTo ClearError
Dim ee4mString As String
ee4mString = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(CellAddress).Address(ReferenceStyle:=xlR1C1)
GetCellString = ExecuteExcel4Macro(ee4mString)
ProcExit:
Exit Function
ClearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Function

Move all pdf files to a new folder

I'd like to copy all files with pdf as extension to a new folder (with name from a cell)
I've created below code:
Public Sub MyFileprojectTF()
Dim startPath As String
Dim myName As String
Dim SourceFileName As String, DestinFileName As String
Dim FSOFile As Object
Dim FSOFolder As Object
FolderName = "C:\Users\320105013\Desktop\DXR\"
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.getfolder(FolderName)
Set FSOFile = FSOFolder.Files
Set fso = CreateObject("Scripting.Filesystemobject")
startPath = "C:\Users\320105013\Desktop\DXR Test files\"
myName = ActiveSheet.Range("B3").Text ' Change as required to cell holding the folder title
If myName = vbNullString Then myName = "Testing"
Dim folderPathWithName As String
folderPathWithName = startPath & Application.PathSeparator & myName
If Dir(folderPathWithName, vbDirectory) = vbNullString Then
MkDir folderPathWithName
Else
MsgBox "Folder already exists"
Exit Sub
End If
ActiveWorkbook.FollowHyperlink startPath & myName
SourceFileName = "C:\Users\320105013\Desktop\DXR\" & (FSOFile)
DestinFileName = startPath & myName & "\"
For Each FSOFile In FSOFile
If FSOFile Like "*.pdf" Then
FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
Next
End Sub
I get the following error:
"Wrong number of arguments"
on FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName.
You are using FSOFile twice as 2 different variables... see the 3 comments I added.
Public Sub MyFileprojectTF()
Dim startPath As String
Dim myName As String
Dim SourceFileName As String, DestinFileName As String
Dim FSOFile As Object
Dim FSOFiles As Object ' ADD THIS
Dim FSOFolder As Object
FolderName = "C:\Users\320105013\Desktop\DXR\"
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.getfolder(FolderName)
Set FSOFiles = FSOFolder.Files ' CHANGE THIS
Set fso = CreateObject("Scripting.Filesystemobject")
startPath = "C:\Users\320105013\Desktop\DXR Test files\"
myName = ActiveSheet.Range("B3").Text ' Change as required to cell holding the folder title
If myName = vbNullString Then myName = "Testing"
Dim folderPathWithName As String
folderPathWithName = startPath & Application.PathSeparator & myName
If Dir(folderPathWithName, vbDirectory) = vbNullString Then
MkDir folderPathWithName
Else
MsgBox "Folder already exists"
Exit Sub
End If
ActiveWorkbook.FollowHyperlink startPath & myName
SourceFileName = "C:\Users\320105013\Desktop\DXR\" & (FSOFile)
DestinFileName = startPath & myName & "\"
For Each FSOFile In FSOFiles ' CHANGE THIS
If FSOFile Like "*.pdf" Then
FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
Next
End Sub
Okay I've changed it to below
but get error message "object doesn't support..." on line FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
Public Sub MyFileprojectTF()
Dim startPath As String
Dim myName As String
Dim SourceFileName As String, DestinFileName As String
Dim FSOFile As Object
Dim FSOFiles As Object
Dim FSOFolder As Object
FolderName = "C:\Users\320105013\Desktop\DXR\"
Set FSOLibrary = CreateObject("Scripting.FileSystemObject")
Set FSOFolder = FSOLibrary.getfolder(FolderName)
Set FSOFiles = FSOFolder.Files
Set fso = CreateObject("Scripting.Filesystemobject")
startPath = "C:\Users\320105013\Desktop\DXR Test files\"
myName = ActiveSheet.Range("B3").Text ' Change as required to cell holding the folder title
If myName = vbNullString Then myName = "Testing"
Dim folderPathWithName As String
folderPathWithName = startPath & Application.PathSeparator & myName
If Dir(folderPathWithName, vbDirectory) = vbNullString Then
MkDir folderPathWithName
Else
MsgBox "Folder already exists"
Exit Sub
End If
ActiveWorkbook.FollowHyperlink startPath & myName
SourceFileName = "C:\Users\320105013\Desktop\DXR\"
DestinFileName = startPath & myName & "\"
For Each FSOFile In FSOFiles
If FSOFile Like "*.pdf" Then
FSOFile.MoveFile Source:=SourceFileName, Destination:=DestinFileName
End If
Next
End Sub
Move Files to a Folder
Using the MoveFile method is the simplest way to go.
The Code
Option Explicit
Public Sub MyFileprojectTF()
Const sFolderPath As String = "C:\Users\320105013\Desktop\DXR\"
Const dStartPath As String = "C:\Users\320105013\Desktop\DXR Test files\"
Const ExtensionPattern As String = "*.pdf"
Dim pSep As String: pSep = Application.PathSeparator
Dim wb As Workbook: Set wb = ThisWorkbook
Dim dFolderName As String
Dim dFolderPath As String
dFolderName = wb.Worksheets("Sheet1").Range("B3").Value
If dFolderName = vbNullString Then
dFolderName = "Testing"
End If
dFolderPath = dStartPath & pSep & dFolderName
If Dir(dFolderPath, vbDirectory) = vbNullString Then
If Dir(sFolderPath & pSep & ExtensionPattern) <> vbNullString Then
MkDir dFolderPath
With CreateObject("Scripting.FileSystemObject")
.MoveFile Source:=sFolderPath & pSep & ExtensionPattern, _
Destination:=dFolderPath
wb.FollowHyperlink dFolderPath
End With
Else
MsgBox "No matching files found in folder '" & sFolderPath & "'."
End If
Else
MsgBox "Folder '" & dFolderPath & "' already exists"
End If
End Sub

Excel InitialFileName Not Working With Period

In the document I have a button to do a save as, this function takes a path and creates the filename based off a cell and the date. This has been working fine until a path came up that has a period in it, it will locate the path correctly but is no longer filling in the filename.
Sub SaveWorkbookAsNewFile()
Dim NewFileType As String
Dim NewFile As String
Dim newfilename As String
Dim cellname As String
Dim monthnum As String
Dim monthtxt As String
Dim daynum As String
Dim yearnum As String
Dim yeartxt As String
Dim SaveArea As String
Dim q As Long
If Worksheets.Count <= 6 Then MsgBox "You must run the report before saving it.", vbInformation, "Save Error": End
SaveArea = Sheet1.Range("K12")
cellname = Sheet1.Range("K20")
'********************************************************************
Dim objFSO As Object, objFolder As Object, objSubFolder As Object
Dim varDirectory As Variant
Dim flag As Boolean
Dim strDirectory As String, goodfolder As String
Dim NumMonth As Integer
NumMonth = 0
q = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(SaveArea)
NumMonth = Month(Date)
For Each objSubFolder In objFolder.subfolders
If InStr(1, UCase(objSubFolder.Name), UCase(MonthName(NumMonth, True)), vbTextCompare) > 1 Then goodfolder = objSubFolder.Name: Exit For
Next objSubFolder
If Not goodfolder = "" Then SaveArea = SaveArea & goodfolder & "\"
'********************************************************************
monthnum = Month(Date)
monthtxt = UCase(MonthName(monthnum, True))
daynum = Day(Date)
yearnum = Year(Date)
yeartxt = Right(yearnum, 2)
newfilename = cellname & "-" & monthtxt & "-" & daynum & "-" & yeartxt
Application.ScreenUpdating = False ' Prevents screen refreshing.
NewFileType = "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm," & _
"All files (*.*), *.*"
NewFile = Application.GetSaveAsFilename( _
InitialFileName:=SaveArea & newfilename, _
fileFilter:=NewFileType)
If NewFile <> "" And NewFile <> "False" Then
ActiveWorkbook.SaveAs FileName:=NewFile, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
CreateBackup:=False, _
ConflictResolution:=xlUserResolution
End If
Application.ScreenUpdating = True
End Sub
A working path (SaveArea) is as follows: \\TestServer\Test\Test\Standards\Test\Test 1\
A broken path (SaveArea) is as follows: \\TestServer\Test\Test\Standards\Test\Test. 1\
Both bring up the save as dialog, but the path with the period does not populate a filename. Is there a way to make this work when the path includes a period?
Edit: I've found a similar post here but it doesn't have a solution to fix the problem.
To get this to work, add the file extension to the InitialFileName parameter like below:
NewFile = Application.GetSaveAsFilename( _
InitialFileName:=SaveArea & newfilename & ".xlsm", _
fileFilter:=NewFileType)

Resources