Just wondering... I have a piece of code - a macro in excel that allows me to open files in a given directory. The thing is that I only want to open .xls files, and the code that I have opens all the files in a given directory.
Can anyone help me with this matter.
Thanks.
Sub FindOpenFiles()
Dim FSO As Scripting.FileSystemObject, folder As Scripting.folder, file As Scripting.file, wb As Workbook
Dim directory As String
directory = "O:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder = FSO.GetFolder(directory)
For Each file In folder.Files
Workbooks.Open file
Next file
End Sub
Sub FindOpenFiles()
Dim FSO As Scripting.FileSystemObject, folder As Scripting.folder, file As Scripting.file, wb As Workbook
Dim directory As String
directory = "O:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folder = FSO.GetFolder(directory)
For Each file In folder.Files
If Mid(file.Name, InStrRev(file.Name, ".") + 1) = "xls" Then
Workbooks.Open directory & Application.PathSeparator & file.Name
End If
Next file
End Sub
This woks fine...
See if this works, may need a tweak or two!
For Each file In folder.Files
If Right(file, 4) = ".xls" Then
Workbooks.Open file
End If
Next file
Try this but I am not really sure
directory = "*.xls"
Related
I'm trying to convert a little over 200 .txt files into .xlsx files. This is the code I'm using:
Dim wb As Excel.Workbook
Dim FSO As New FileSystemObject
Dim obj_folder As Object
Dim file As Object
Dim path As String
Dim destination As String
Dim file_name As String
path = "C:\Users\ABCD\Desktop\Attributes Files\"
destination = "C:\Users\ABCD\Desktop\Attributes xlx\"
Set FSO = CreateObject("Scripting.filesystemobject")
Set obj_folder = FSO.GetFolder(path)
For Each file In obj_folder.Files
file_name = Left(file.Name, (InStrRev(file.Name, ".", -1, vbTextCompare) - 1))
Call Workbooks.OpenText(Filename:=file, DataType:=xlDelimited, Tab:=True)
Set wb = ActiveWorkbook
wb.SaveAs Filename:=destination & file_name & ".xlsx"
wb.Close savechanges:=False
Next file
When the code is finished running and I go to open the .xlsx workbook, I receive an error that states Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.
I'm not sure what to do here as I know this works when I manually change one .txt file workbook to a .xlsx file type. I even recorded the macro and it more or less matches up with my code that I have here. (on one attempt I even copied down the recorded macro exactly and it still wouldn't let me open the .xlsx file after it finished.) Any help would be appreciated.
You never cite what file format you save in. You want to use xlOpenXMLWorkbook = 51
It looks like you pass the object file to the Filename paramter of open. I would use file.Name just like you do when you are building the output name.
Using a With block will gracefully handle the workbook object for you.
FSO.GetBaseName will remove the extension of the filename for you.
Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.filesystemobject")
Dim path As String
path = "C:\Users\ABCD\Desktop\Attributes Files\"
Dim destination As String
destination = "C:\Users\ABCD\Desktop\Attributes xlx\"
Dim file As Object
For Each file In FSO.GetFolder(path).Files
Dim file_name As String
file_name = FSO.GetBaseName(file.Name)
With Workbooks.OpenText(Filename:=file.Name, DataType:=xlDelimited, Tab:=True)
.SaveAs Filename:=destination & file_name & ".xlsx", FileFormat:=51
.Close savechanges:=False
End With
Next file
I have a little problem with my code in VBA, How can I exclude the other extension file like .txt, .csv, .xlsx, and .xlsm so I can select only in my For Each Loop is the .PDF extension only.
I've already searched about this issue and already tried, But the solution is not applicable in my code.
This is my code:
Option Explicit
Sub GetPDFFile()
Dim mainWs As Worksheet
Dim pdfPath As Variant, excelPath As Variant
Dim fileSystemObject As New fileSystemObject
Dim getFolderPath As Folder
Dim getFile As file
Dim wb As Workbook
Set mainWs = ThisWorkbook.Sheets("Main")
pdfPath = mainWs.Range("C7").Value
excelPath = mainWs.Range("C8").Value
'Set all variable to null
Call SetNothing
If pdfPath = "" Then
Call MsgActionInvalid("Please input PDF File Folder.")
ElseIf excelPath = "" Then
Call MsgActionInvalid("Please input Output Folder Location.")
Else
Set getFolderPath = fileSystemObject.getFolder(pdfPath)
Set wa = CreateObject("word.application")
If cntFiles <> 0 Then
For Each getFile In getFolderPath.Files
`Other code............
Next
End Sub
I'm getting all the files inside the folder that I've selected. So inside the For Each Loop I'm getting a debug message because the file is not .PDF.
Any ideas about this guys?
Thanks in advance.
Use the Type property of the File object like getFile.Type to find out its type. And use a If statement to run your Other code............ only on the desired type of files.
Alternatively use UCase(getFile) Like "*.PDF" to make sure that it is not case sensitive. Otherwise you only trigger .PDF but not .Pdf or .pdf or .pDf or whatever.
Which is the same as UCase(Right$(getFile, 4)) = ".PDF"
You should be using Right to check the file extension. Something like:
For Each getFile In getFolderPath.Files
If Right(getFile, 4) = ".pdf" Then
' have found a PDF extension............
End If
Next
Regards,
I have a question regarding looping through a folder of two different kinds of files: xlsm and mdb (Access).
I have currently written a macro that would open 1 single xlsm file and 1 single mdb file before copying some data from the xlsm to mdb file and then saving the mdb file.
Now, I would like this process to repeat through a folder that has 50 xlsm files and 50 mdb files. They have the same names, so for example the loop should do this:
Open both xlsm and mdb files called "2001".
Perform copying and pasting etc from xlsm to mdb (I have written this part).
Save the mdb file.
Close both xlsm and mdb files called "2001".
Repeat steps 1-4 for "2002", "2003", etc in the folder.
I am really new to VBA so much help is appreciated! Looking forward to any guidance at all. Merry Christmas!
I just did today sample code for listing JPG files in folder, you can adopt and modify to do exactly what you like it to do, but would be very hard to give you exact code without being able to see your solution.
Public Sub listImages(folderPath As String)
'define variables
Dim fso As Object
Dim objFolder As Object
Dim objFolders As Object
Dim objF As Object
Dim objFile As Object
Dim objFiles As Object
Dim strFileName As String
Dim strFilePath As String
Dim myList As String
'set file system object
Set fso = CreateObject("Scripting.FileSystemObject")
'set folder object
Set objFolder = fso.GetFolder(folderPath)
'set files
Set objFiles = objFolder.files
Set objFolders = objFolder.subfolders
'list all images in folder
For Each objFile In objFiles
If Right(objFile.Name, 4) = ".jpg" Then
strFileName = objFile.Name
strFilePath = objFile.Path
myList = myList & strFileName & " - " & strFilePath & vbNewLine
End If
Next
'go through all subflders
For Each objF In objFolders
Call listImages(objF.Path)
Next
Debug.Print myList
Set objFolder = Nothing
Set objFile = Nothing
Set fso = Nothing
End Sub
This is my first post so I apologize if I fail to give enough information. I'll do my best.
I am attempting to scan through a specific folder and open the most recently titled Excel file. The files are named '9 1 13' and '9 2 13' ect. My sub correctly steers itself to the right folder and identifies the most recent file. However, when I attempt to open it, I get a runtime error 1004.
File '9 2 13.xlsx' could not be found, check spelling....
It clearly has found the right file and path to it, so why can't VBA open it? My current sub is below. Before anyone asks, the file path '\\Hsrkdfs\hsdata\rk\grp06....' is because I am pulling from a network where everyone's network access isn't mapped the same. Some access this folder from the G: drive, others the R:, and this macro must be functional from all computers. The error occurs on the 'Workbooks.Open strFilename line.
Sub GetMostRecentFile()
Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date
'set path for files - CHANGE FOR YOUR APPROPRIATE FOLDER
Const myDir As String = "\\Hsrkdfs\hsdata\rk\grp06\Rockford Repair Station Quality\DELIVERY\Daily Status report - commercial"
'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)
'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
If objFile.DateLastModified > dteFile Then
dteFile = objFile.DateLastModified
strFilename = objFile.Name
End If
Next objFile
Workbooks.Open strFilename
Set FileSys = Nothing
Set myFolder = Nothing
End Sub
Try using .Path which returns the full path, rather than .Name, which only returns the name and extension of the file.
strFilename = objFile.Path
I want to read certain excel files from a directory and then open them in excel-2007 with VBA.
Here is an example:
directory: c:\temp
file pattern: is xxxxx0123.xls (xxxxx represents the file names).
I try to use Application.FileSearch, but it won't work in Excel 2007. Does any one have good suggestions?
Thanks in advance
You can use DIR to find files matching your pattern, ie this code opens these files, grabs their path, and closes the files again
The code can be made recursive if you need to look in sub-folders
Sub GetFiles()
Dim strFolder As String
Dim strFileName As String
Dim wb As Workbook
strFolder = "C:\temp"
strFileName = Dir(strFolder & "\*123.xls")
Do While Len(strFileName) > 0
Set wb = Workbooks.Open(strFileName)
Debug.Print wb.FullName
wb.Close False
strFileName = Dir
Loop
End Sub