VBA - Complex File Opening - vba

I currently have coded how to open all files in a certain folder
Dim MyFolder As String
Dim MyFile As String
MyFolder = "K:\Data Directories\Acquisitions"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While Len(MyFile) > 0
Workbooks.Open FileName:=MyFolder & "\" & MyFile
MyFile = Dir
Loop
Now I'm trying to open all files in multiple folders that have the same name.
For instance:
Dim MyFolder As String
Dim MyFile As String
Dim MyFolder2 As String
MyFolder = "K:\Data Directories\Acquisitions"
MyFolder2 = MyFolder & "*\June 2015"
MyFile = Dir(MyFolder2 & "\*.xlsx")
Do While Len(MyFile) > 0
Workbooks.Open FileName:=MyFolder2 & "\" & MyFile
MyFile = Dir
Loop
The problem is the * that I place before June 2015. It comes out as an actual "*" in the path code instead of a wildcard.
The code is meant to choose all folders in the Acquisition directory, and then look inside them for a June 2015 folder. From there, all the Excel files in these multiple June 2015 folders should be opened. What am I doing wrong?

I think this will do what you want. Give it a try and see what happens.
Sub DoFolderPart1()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "K:\Data Directories\Acquisitions"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Sub DoFolder(Folder)
Dim SubFolder
Dim strName As String
Dim pos As Integer
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
strName = Folder.name
pos = InStr(strName, "June 2015")
If pos > 0 Then
For Each File In Folder.Files
If Right(File, 4) = "xlsx" Then
Workbooks.Open Filename:=File
End If
Next
End If
End Sub
I based my answer on this loop-through-all-subfolders-using-vba

Related

VBA producing most recently modified .XLS file in a folder

What VBA code can I use to use a folder path displayed in a cell to retrieve the most recently modified .xls file within that folder? So far, I have filenames showing but not the correct files:
Function GetFileNames(ByVal FolderPath As String) As Variant
Dim Result As Variant
Dim i As Integer
Dim MyFile As Object
Dim MyFSO As Object
Dim MyFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set MyFolder = MyFSO.GetFolder(FolderPath)
Set MyFiles = MyFolder.Files
ReDim Result(1 To MyFiles.Count)
i = 1
For Each MyFile In MyFiles
Result(i) = MyFile.Name
i = i + 1
Next MyFile
GetFileNames = Result
End Function
I think that what you are looking for is something like the selected answer for this question.
You could adapt the code to fit your specific needs of passing the argument inside the like the function below. Note that the argument directory must include the backward slash at the end (eg. "C:\Users\").
Function NewestFile(Directory As String) As String
'PURPOSE: Get the newest file name from specified directory
Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String
'Specify the file type, if any
FileSpec = "*.xls"
FileName = Dir(Directory & FileSpec)
If FileName <> "" Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
Do While FileName <> ""
If FileDateTime(Directory & FileName) > MostRecentDate Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
End If
FileName = Dir
Loop
End If
NewestFile = MostRecentFile
End Function
EDIT: For more flexibility, you can also add the option (like in PeterT's revised answer) to search for another type of file with the optional FileSpec argument like in the alternative function below. For this function, if you don't provide any value for FileSpec, it will look at all files.
Function NewestFile(ByVal Directory As String, Optional ByVal FileSpec As String = "*.*") As String
'PURPOSE: Get the newest .xls file name from
Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
'Specify the file type, if any
FileName = Dir(Directory & FileSpec)
If FileName <> "" Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
Do While FileName <> ""
If FileDateTime(Directory & FileName) > MostRecentDate Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
End If
FileName = Dir
Loop
End If
NewestFile = MostRecentFile
End Function
Speed issue: Dir Function vs FileSystemObject
In terms of speed, if the folder you want to look at contains a small number of files, the 2 methods will give you the same results in roughly the same amount of time. However, if you have a lot of files in that folder, using the Dir Function approach instead of the FileSystemObject should speed up greatly the execution of your macro. I haven't tested it, but that seems to be what was concluded from the answers in this question.
You just need to check the DateLastModified timestamp of each file in the folder. A quick check to see if it's the most recent will "sort" it to the top.
Option Explicit
Sub test()
Debug.Print "most recently modified file is " & GetNewestModifiedFilename("C:\Temp")
End Sub
Function GetNewestModifiedFilename(ByVal folderPath As String, _
Optional fileType As String = "xls*") As String
Dim MyFSO As Object
Dim MyFolder As Object
Dim MyFiles As Object
Set MyFSO = CreateObject("Scripting.FileSystemObject")
Set MyFolder = MyFSO.GetFolder(folderPath)
Set MyFiles = MyFolder.Files
Dim mostRecentFilename As String
Dim mostRecentTimestamp As Date
Dim MyFile As Object
For Each MyFile In MyFiles
Debug.Print MyFile.Name & ", modified " & MyFile.DateLastModified
If Mid(MyFile.Name, InStrRev(MyFile.Name, ".") + 1) Like fileType Then
If MyFile.DateLastModified > mostRecentTimestamp Then
mostRecentFilename = MyFile.Name
mostRecentTimestamp = MyFile.DateLastModified
End If
End If
Next MyFile
GetNewestModifiedFilename = mostRecentFilename
End Function

How to convert all *.potx files to *.pptx files with VBA?

I have a folder of ~20 *.potx files and I would like to convert all *.potx files to *.pptx, then delete the *.potx files.
The following will loop through all your templates, convert, and delete the template files.
Sub loopFiles()
Dim fso As New FileSystemObject
Dim fil As File
Dim fold As Folder
Set fold = fso.GetFolder(yourFolder)
For Each fil In fold.Files
If InStr(1, fil.Name, ".potx") > 0 Then
Application.Presentations.Open fil.Path
ActivePresentation.SaveAs Replace(fil.Path, ".potx", ".pptx"), ppSaveAsDefault
ActivePresentation.Close
'if you truly want to delete them, don't recommend since they are .potx
fil.Delete True
End If
Next fil
End Sub
You could try something like this: (replace YOUR FOLDER HERE with your folder name)
Public Sub ConvertPP()
Dim pApp As Object
Set pApp = CreateObject("Powerpoint.Application")
Dim sFile As String
Dim sFolder As String
sFolder = "YOUR FOLDER HERE"
sFile = Dir(sFolder & "\*.potx")
Do Until sFolder = ""
pApp.Presentations.Open sFolder & "\" & sFile
pApp.ActivePresentation.SaveAs sFolder & "\" & Replace(sFile, "potx", "pptx"), 11
pApp.ActivePresentation.Close
sFile = Dir()
Loop
pApp.Quit
Set pApp = Nothing
End Sub

Move the csv file(s) from the active folder to the sub-folder "archive"

The file is identified (GWB) but jams at the destination command. What am I missing?
Sub MoveCsvFiles()
Dim Wkb As Workbook
Dim SFile As String 'source file
Dim GWB As String
Set Wkb = ThisWorkbook
SFile = Wkb.Path & "\"
GWB = Dir(SFile & "*.csv")
Do While Len(GWB) > 1
Set FSO = CreateObject("scripting.filesystemobject")
FSO.MoveFile Source:=Wkb.Path, Destination:=Wkb.Path & "\Archive\"
GWB = Dir
Loop
End Sub
Found the problem. Source file not identified properly. Thanks all
FSO.MoveFile Source:=Wkb.Path & "\" & GWB, Destination:=Wkb.Path & "\Archive\"

I would like to change a worksheets name to the filename during a loop as I open its workbook VBA

I am currently using this code to open all .xls files in a folder
Sub OpenFiles()
Dim MyFolder As String
Dim MyFile As String
MyFolder = InputBox("Please enter the folder for files")
MyFile = Dir(MyFolder & "\*.xls")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyFile
****Sheet1.Name = "MyFile"****
MyFile = Dir
Loop
End Sub
I am trying to change the worksheet name to the file name as it loops though
Every worksheet I am opening will be called "Parts List"
I am trying to use the asterisk portion to do this but it does not work.
This will rename the Worksheets("Parts List") in the newly opened workbook to MyFile.
Sub OpenFiles()
Dim wb As Workbook
Dim MyFolder As String
Dim MyFile As String
MyFolder = InputBox("Please enter the folder for files")
MyFile = Dir(MyFolder & "\*.xls")
Do While MyFile <> ""
Set wb = Workbooks.Open(Filename:=MyFolder & "\" & MyFile)
wb.Worksheets("Parts List").Name = MyFile
MyFile = Dir
Loop
End Sub
Try changing the line to:
Sheets("Sheet1").Name = "MyFile"

Publisher VBA to save as image

I've developed the following code to save all publisher files in the current directory as an image, however it seems to take a long time to run through. Also, I can't figure out a way to exclude the current file that the macro is running from. Anyone got any ideas?
Sub Looptest()
Dim MyFile As String, Sep As String
Dim objPub As Object
Set objPub = CreateObject("Publisher.Application")
Dim folder As String
folder = CurDir()
If Len(Dir(folder & "\" & "jpg", vbDirectory)) = 0 Then
MkDir (folder & "\" & "jpg")
End If
Sep = Application.PathSeparator
If Sep = "\" Then
' Windows platform search syntax.
MyFile = Dir(CurDir() & Sep & "*.pub")
Else
MyFile = Dir("", MacID("XLS5"))
End If
' Starts the loop, which will continue until there are no more files
' found.
Do While MyFile <> ""
'If MyFile = "macro.pub" Then
'GoTo ContinueLoop
'End If
Dim pubApp As Publisher.Application
Dim pubDoc As Publisher.Document
Dim folder2 As String
folder2 = CurDir() & Sep & MyFile
Set pubApp = New Publisher.Application
pubApp.Open folder2
'pubApp.ActiveWindow.Visible = True
num = folder2
pubApp.ActiveDocument.Pages(1).SaveAsPicture CurDir() & Sep & "jpg" & "\" & MyFile & ".jpg"
pubApp.Quit
MyFile = Dir()
'ContinueLoop:
Loop
End Sub
I've commented out my attempt at skipping the file (called Macro.pub in this instance), as it just seemed to stall and not go anywhere.
Any help would be greatly appreciated!
-Cr1kk0
Assuming your code is correct in all other respects, this might do the trick
If MyFile = ActiveDocument.FullName Then
GoTo ContinueLoop
End If
I'm guessing your check fails because you're comparing a short file name to a full file name. (You could also just hardcode the entire path to macro.pub)