Hi I am trying to list all the files in a subdirectory of where the Excel workbook is residing in. For some reason, the code cannot execute beyond the Dir function. Can anyone please advise? Thank you!
Sub ListFiles()
ActiveSheet.Name = "temp"
Dim MyDir As String
'Declare the variables
Dim strPath As String
Dim strFile As String
Dim r As Long
MyDir = ActiveWorkbook.Path 'current path where workbook is
strPath = MyDir & ":Current:" 'files within "Current" folder subdir, I am using Mac Excel 2011
'Insert the headers in Columns A, B, and C
Cells(1, "A").Value = "FileName"
Cells(1, "B").Value = "Size"
Cells(1, "C").Value = "Date/Time"
'Find the next available row
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
'Get the first file from the folder
'Note: macro stops working here
strFile = Dir(strPath & "*.csv", vbNormal)
'Loop through each file in the folder
Do While Len(strFile) > 0
'List the name, size, and date/time of the current file
Cells(r, 1).Value = strFile
Cells(r, 2).Value = FileLen(strPath & strFile)
Cells(r, 3).Value = FileDateTime(strPath & strFile)
'Determine the next row
r = r + 1
'Get the next file from the folder
strFile = Dir
Loop
'Change the width of the columns to achieve the best fit
Columns.AutoFit
End Sub
Gianna, you cannot use DIR like that in VBA-EXCEL 2011. I mean the wildcards are not supported. You have to use MACID for this purpose.
See this code sample (TRIED AND TESTED)
Sub Sample()
MyDir = ActiveWorkbook.Path
strPath = MyDir & ":"
strFile = Dir(strPath, MacID("TEXT"))
'Loop through each file in the folder
Do While Len(strFile) > 0
If Right(strFile, 3) = "csv" Then
Debug.Print strFile
End If
strFile = Dir
Loop
End Sub
See this link for more details on MACID
Topic: MacID Function
Link: http://office.microsoft.com/en-us/access-help/macid-function-HA001228879.aspx
EDIT:
In case that link ever dies which I doubt, here is an extract.
MacID Function
Used on the Macintosh to convert a 4-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.
Syntax
MacID(constant)
The required constant argument consists of 4 characters used to specify a resource type, file type, application signature, or Apple Event, for example, TEXT, OBIN, "XLS5" for Excel files ("XLS8" for Excel 97), Microsoft Word uses "W6BN" ("W8BN" for Word 97), and so on.
Remarks
MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support * and ? as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns TEXT type files from the current folder:
Dir("SomePath", MacID("TEXT"))
MacID is used with Shell and AppActivate to specify an application using the application's unique signature.
HTH
If Dir(outputFileName) <> "" Then
Dim ans
ans = MsgBox("File already exists.Do you wish to continue(the previous file will be deleted)?", vbYesNo)
If ans = vbNo Then
Exit Sub
Else
Kill outputFileName
End If
End If
For listitem = 0 To List6.ListCount() - 1
For the answer above, it worked for me when I took out the "TEXT" in MacID:
Sub LoopThruFiles()
Dim mydir As String
Dim foldercount As Integer
Dim Subjectnum As String
Dim strpath As String
Dim strfile As String
ChDir "HD:Main Folder:"
mydir = "HD:Main Folder:"
SecondaryFolder = "Folder 01:"
strpath = mydir & SecondaryFolder
strfile = Dir(strpath)
'Loop through each file in the folder
Do While Len(strfile) > 0
If Right(strfile, 3) = "cef" Then
MsgBox (strfile)
End If
strfile = Dir
Loop
End Sub
Related
So, I renamed and moved some workbooks that are linked together and I need to update their xlExcelLinks on VBA, the thing is, I have a list of the references to update, but I can't figure out how to update only the ones I need and not every reference on the book.
The initial idea was to search for matching strings between a file name and the stored reference's path. Example data:
A2 Cell on Data.xlsx
Change to
I have this guide example code:
Sub Relink()
Dim previousFile, newFile, oldPath, newPath, Macro, altTab As String
'Macro stores the name of the file running the macro and altTab the name of the file to update
Dim ref as xlExcelLink 'Clearly not a type of data but I need something similar
Windows(Macro).activate
For I = 2 To 4
oldPath = Range("L"& I).Value
newPath = Range("M" & I).Value
previousFile = Range("N" & I).Value
newFile = Range("O" & I).Value
Windows(alTab).activate
'Somehow check for every reference avoiding itself
If ref.Address = oldPath & "\" & previousFile Then
ActiveWorkbook.ChangeLink Name:=oldPath & "\" & previousFile, _
NewName:=newPath & "\" & newFile, Type:=xlExcelLinks
End If
Next
End Sub
Note that on some files there could be only 1 update needed from 50ish references.
Try this code:
Sub UpdateLinks()
'Reference to your change list.
'ThisWorkbook is the file containing this code.
Dim ChangeList As Range
Set ChangeList = ThisWorkbook.Worksheets("Sheet2").Range("A2:D4")
'The workbook containing the links to change.
Dim wrkBk As Workbook
Set wrkBk = Workbooks("Test Timesheet.xlsx")
'If workbook isn't open use:
'Set wrkbk = workbooks.Open(<path to workbook>)
'Look at each link in the workbook.
'lnk must be Variant so it can be used in the For Each loop.
Dim lnk As Variant
For Each lnk In wrkBk.LinkSources
Dim OldPath As String
OldPath = Left(lnk, InStrRev(lnk, "\") - 1)
Dim OldFileName As String
OldFileName = Mid(lnk, InStrRev(lnk, "\") + 1, Len(lnk))
'Search for the existing path in first column of ChangeList.
Dim FoundLink As Range
Set FoundLink = ChangeList.Columns(1).Find(OldPath, , xlValues, xlWhole, xlByRows, xlNext)
'If it's not found, then continue to the next link.
'If it is found check that OldName also exists on that line, if it doesn't then continue searching.
If Not FoundLink Is Nothing Then
Dim firstAdd As String
firstAdd = FoundLink.Address
Do
If FoundLink.Offset(, 2) = OldFileName Then
'Found the link we're after so exit the loop.
Dim NewPath As String
NewPath = FoundLink.Offset(, 1)
Dim NewFileName As String
NewFileName = FoundLink.Offset(, 3)
Exit Do
Else
'Continue searching.
Set FoundLink = ChangeList.Columns(1).FindNext(FoundLink)
End If
Loop While firstAdd <> FoundLink.Address
'Make the change.
wrkBk.ChangeLink Name:=OldPath & Application.PathSeparator & OldFileName, _
NewName:=NewPath & Application.PathSeparator & NewFileName
End If
Next lnk
End Sub
Hi I am trying to list all the files in a subdirectory of where the Excel workbook is residing in. For some reason, the code cannot execute beyond the Dir function. Can anyone please advise? Thank you!
Sub ListFiles()
ActiveSheet.Name = "temp"
Dim MyDir As String
'Declare the variables
Dim strPath As String
Dim strFile As String
Dim r As Long
MyDir = ActiveWorkbook.Path 'current path where workbook is
strPath = MyDir & ":Current:" 'files within "Current" folder subdir, I am using Mac Excel 2011
'Insert the headers in Columns A, B, and C
Cells(1, "A").Value = "FileName"
Cells(1, "B").Value = "Size"
Cells(1, "C").Value = "Date/Time"
'Find the next available row
r = Cells(Rows.Count, "A").End(xlUp).Row + 1
'Get the first file from the folder
'Note: macro stops working here
strFile = Dir(strPath & "*.csv", vbNormal)
'Loop through each file in the folder
Do While Len(strFile) > 0
'List the name, size, and date/time of the current file
Cells(r, 1).Value = strFile
Cells(r, 2).Value = FileLen(strPath & strFile)
Cells(r, 3).Value = FileDateTime(strPath & strFile)
'Determine the next row
r = r + 1
'Get the next file from the folder
strFile = Dir
Loop
'Change the width of the columns to achieve the best fit
Columns.AutoFit
End Sub
Gianna, you cannot use DIR like that in VBA-EXCEL 2011. I mean the wildcards are not supported. You have to use MACID for this purpose.
See this code sample (TRIED AND TESTED)
Sub Sample()
MyDir = ActiveWorkbook.Path
strPath = MyDir & ":"
strFile = Dir(strPath, MacID("TEXT"))
'Loop through each file in the folder
Do While Len(strFile) > 0
If Right(strFile, 3) = "csv" Then
Debug.Print strFile
End If
strFile = Dir
Loop
End Sub
See this link for more details on MACID
Topic: MacID Function
Link: http://office.microsoft.com/en-us/access-help/macid-function-HA001228879.aspx
EDIT:
In case that link ever dies which I doubt, here is an extract.
MacID Function
Used on the Macintosh to convert a 4-character constant to a value that may be used by Dir, Kill, Shell, and AppActivate.
Syntax
MacID(constant)
The required constant argument consists of 4 characters used to specify a resource type, file type, application signature, or Apple Event, for example, TEXT, OBIN, "XLS5" for Excel files ("XLS8" for Excel 97), Microsoft Word uses "W6BN" ("W8BN" for Word 97), and so on.
Remarks
MacID is used with Dir and Kill to specify a Macintosh file type. Since the Macintosh does not support * and ? as wildcards, you can use a four-character constant instead to identify groups of files. For example, the following statement returns TEXT type files from the current folder:
Dir("SomePath", MacID("TEXT"))
MacID is used with Shell and AppActivate to specify an application using the application's unique signature.
HTH
If Dir(outputFileName) <> "" Then
Dim ans
ans = MsgBox("File already exists.Do you wish to continue(the previous file will be deleted)?", vbYesNo)
If ans = vbNo Then
Exit Sub
Else
Kill outputFileName
End If
End If
For listitem = 0 To List6.ListCount() - 1
For the answer above, it worked for me when I took out the "TEXT" in MacID:
Sub LoopThruFiles()
Dim mydir As String
Dim foldercount As Integer
Dim Subjectnum As String
Dim strpath As String
Dim strfile As String
ChDir "HD:Main Folder:"
mydir = "HD:Main Folder:"
SecondaryFolder = "Folder 01:"
strpath = mydir & SecondaryFolder
strfile = Dir(strpath)
'Loop through each file in the folder
Do While Len(strfile) > 0
If Right(strfile, 3) = "cef" Then
MsgBox (strfile)
End If
strfile = Dir
Loop
End Sub
I am attempting to use VBA to open all the excel files in a directory (in this case c:\temp) and put all the files datasheets in one large file. Each new sheet is named with the filename plus the name of the sheet on the original document. The code that I have copies the first file's first sheet and even names it correctly, but then fails with a Run-time error 1004: Application defined or object defined error on the second sheet when I try to set the name. Anyone have any suggestions on how to fix.
Sub MergeAllWorkbooks()
Dim FolderPath As String
Dim FileName As String
' Create a new workbook
Set FileWorkbook = Workbooks.Add(xlWBATWorksheet)
' folder path to the files you want to use.
FolderPath = "C:\Temp\"
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
Dim currentSheet As Worksheet
Dim sheetIndex As Integer
sheetIndex = 1
Windows(WorkBk.Name).Activate
For Each currentSheet In WorkBk.Worksheets
currentSheet.Select
currentSheet.Copy Before:=Workbooks(FileWorkbook.Name).Sheets(sheetIndex)
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
sheetIndex = sheetIndex + 1
Next currentSheet
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
End Sub
Replace
FileWorkbook.Sheets(sheetIndex).Name = FileName & "-" & currentSheet.Name
with (I separated it out for readability)
sWSName = FileName & "-" & currentSheet.Name
sWSName = NameTest(sWSName)
sWSName = TestDup(sWSName)
FileWorkbook.Sheets(sheetIndex).Name = sWSName
You will need to define the sWSName.
Below are the modified functions I have previously used.
Function NameTest(sName As String) As String
NameTest = sName
aSpecChars = Array("\", "/", "*", "[", "]", ":", "?")
For Each c In aSpecChars
NameTest = Replace(NameTest, c, "")
Next c
If Len(sName) > 31 Then NameTest = Left(sName, 31)
End Function
Function TestDup(sWSName As String) As String
TestDup = sWSName
For Each ws In Worksheets
Debug.Print ws.Name
If sWSName = ws.Name Then TestDup = TestDup(Left(sWSName, Len(sWSName) - 1))
Next ws
End Function
If posting this code (or to this extent) is out of line please let me know as I am still coming to terms with the level of effort require versus reasonable response.
I'm trying to combine several excel files into one. For this I've been using and modifying an old answer I found here, but I ran into trouble while running it on Excel 2016 for Mac (it worked ok with Excel 2011 for Mac, with some changes).
In Excel 2016 (Mac), the following code runs through the loop once, after which it prints the name of the first file in the selected folder, but then it stops.
In Excel 2011 (Mac), it correctly prints the names of all files in the selected folder.
Sub wat()
Dim FilesFolder As String, strFile As String
'mac excel 2011
'FilesFolder = MacScript("(choose folder with prompt ""dis"") as string")
'mac excel 2016
FilesFolder = MacScript("return posix path of (choose folder with prompt ""dat"") as string")
If FilesFolder = "" Then Exit Sub
strFile = Dir(FilesFolder)
Do While Len(strFile) > 0
Debug.Print "1. " & strFile
strFile = Dir
Loop
MsgBox "ded"
End Sub
So, I'm pretty new at this, but it looks to me like strFile = Dir is not working properly.
I looked at the Ron deBruin page:
Loop through Files in Folder on a Mac (Dir for Mac Excel)
but to be honest that was a little too complicated for me to comprehend and modify to my needs.
Any help is appreciated, and thanks for the patience!
Option Explicit
Sub GetFileNames()
'Modified from http://www.rondebruin.nl/mac/mac013.htm
Dim folderPath As String
Dim FileNameFilter As String
Dim ScriptToRun As String
Dim MyFiles As String
Dim Extensions As String
Dim Level As String
Dim MySplit As Variant
Dim FileInMyFiles As Long
Dim Fstr As String
Dim LastSep As String
'mac excel 2016
'Get the directory
On Error Resume Next 'MJN
folderPath = MacScript("choose folder as string") 'MJN
If folderPath = "" Then Exit Sub 'MJN
On Error GoTo 0 'MJN
'Set up default parameters to get one level of Folders
'All files
Level = "1"
Extensions = ".*"
'Set up filter for all file types
FileNameFilter = "'.*/[^~][^/]*\\." & Extensions & "$' " 'No Filter
'Set up the folder path to allow to work in script
folderPath = MacScript("tell text 1 thru -2 of " & Chr(34) & folderPath & _
Chr(34) & " to return quoted form of it's POSIX Path")
folderPath = Replace(folderPath, "'\''", "'\\''")
'Run the script
ScriptToRun = ScriptToRun & "do shell script """ & "find -E " & _
folderPath & " -iregex " & FileNameFilter & "-maxdepth " & _
Level & """ "
'Set the String MyFiles to the result of the script for processing
On Error Resume Next
MyFiles = MacScript(ScriptToRun)
On Error GoTo 0
'Clear the fist four columns of the current 1st sheet on the workbook
Sheets(1).Columns("A:D").Cells.Clear
'Split MyFiles and loop through all the files
MySplit = Split(MyFiles, Chr(13))
For FileInMyFiles = LBound(MySplit) To UBound(MySplit)
On Error Resume Next
Fstr = MySplit(FileInMyFiles)
LastSep = InStrRev(Fstr, Application.PathSeparator, , 1)
Sheets(1).Cells(FileInMyFiles + 1, 1).Value = Left(Fstr, LastSep - 1) 'Column A - Directory
Sheets(1).Cells(FileInMyFiles + 1, 2).Value = Mid(Fstr, LastSep + 1, Len(Fstr) - LastSep) 'Column B - file name
Sheets(1).Cells(FileInMyFiles + 1, 3).Value = FileDateTime(MySplit(FileInMyFiles)) 'Column C - Date
Sheets(1).Cells(FileInMyFiles + 1, 4).Value = FileLen(MySplit(FileInMyFiles)) 'Column D - size
On Error GoTo 0
Next FileInMyFiles
'Fit the contents
Sheets(1).Columns("A:D").AutoFit
End Sub
I need the VBA code to import selected spreadsheets from multiple excel files into access 2007 table.
Can anyone help?
This is the code I have so far.
Option Compare Database
Option Explicit
Const strPath As String = "C:\Users\person\Documents\files.xlsx"
Dim strFile As String
Dim strFileList() As String
Dim intFile As Integer
Sub Sample()
strFile = Dir(strPath & "*.xls")
strFile = Dir(strPath & "*.xls")
While strFile <> ""
'adding files to the list
intFile = intFile + 1
ReDim Preserve strFileList(1 To intFile)
strFileList(intFile) = strFile
strFile = Dir()
If intFile = 0 Then
MsgBox "No Files Found"
Exit Sub
End If
'going through the files and linking them to access
For intFile = 1 To UBound(strFileList)
DoCmd.TransferSpreadsheet acLink, , _
strFileList(intFile), strPath & strFileList(intFile), True, "A5:J17"
Next
MsgBox UBound(strFileList) & "Files were linked"
End Sub
I don't understand all of what's going on with that code, but my hunch is it's not doing what you expect.
You declare a constant, strPath.
Const strPath As String = "C:\Users\person\Documents\files.xlsx"
Later, you concatenate "*.xls" to that constant and feed it to the Dir() function.
Sub Sample()
strFile = Dir(strPath & "*.xls")
I think you should try Debug.Print at that point ...
Debug.Print strPath & "*.xls"
... because the string you're giving Dir() makes it equivalent to this statement:
strFile = Dir("C:\Users\person\Documents\files.xlsx*.xls")
I doubt that matches any of the Excel files you want to process.
See whether the following code outline is useful. I don't see a need to first populate an array, then cycle through the array to link the spreadsheets. I don't see why you should need an array at all here. Avoid it if you can because the code will be simpler and ReDim Preserve is a performance-killer.
Sub Sample2()
Const cstrFolder As String = "C:\Users\person\Documents\"
Dim strFile As String
Dim i As Long
strFile = Dir(cstrFolder & "*.xls")
If Len(strFile) = 0 Then
MsgBox "No Files Found"
Else
Do While Len(strFile) > 0
Debug.Print cstrFolder & strFile
' insert your code to link to link to it here '
i = i + 1
strFile = Dir()
Loop
MsgBox i & " Files were linked"
End If
End Sub