I have a visual basic macro (shown below) in a master sheet that imports all of the csv files in the root folder of the master tally file. This works great if the beginning of the files have explicitly different names. But many times the csv files I get are named such that the sheet tab name that is set to the csv file name truncates making the macro fail because the second file it imports has the same truncated name (gives me a name error). I am trying to get the correct syntax to get the names of the tabs changed to the count value (Fnum) “-“ then the truncated csv file name. Any help from a savvy visual basic guru would be greatly appreciated.
![]()
Sub ImportFiles() Dim MyPath As String Dim FilesInPath As String Dim MyFiles() As String Dim SourceRcount As Long Dim Fnum As Long Dim mybook As Workbook Dim basebook As Workbook 'Fill in the path\folder where the files are 'on your machine 'MyPath = "C:\Users\dlweb_000\Desktop\GPX2KMZ Open Converter\Output" 'Set path with excel sheet cell value 'MyPath = Range("A2").Value 'use path of current excel sheet locaiton MyPath = ActiveWorkbook.Path & "\" 'Add a slash at the end if the user forget it If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\" End If 'If there are no Excel files in the folder exit the sub FilesInPath = Dir(MyPath & "*.csv") If FilesInPath = "" Then MsgBox "No files found" Exit Sub End If On Error GoTo CleanUp Application.ScreenUpdating = False Set basebook = ThisWorkbook 'Fill the array (myFiles) with the list of files in the folder Fnum = 0 Do While FilesInPath <> "" Fnum = Fnum + 1 ReDim Preserve MyFiles(1 To Fnum) MyFiles(Fnum) = FilesInPath FilesInPath = Dir() Loop 'Loop through all files in the array (myFiles) If Fnum > 0 Then For Fnum = LBound(MyFiles) To UBound(MyFiles) Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum)) mybook.Worksheets(1).Copy After:= _ basebook.Sheets(basebook.Sheets.Count) On Error Resume Next ActiveSheet.Name = mybook.Name On Error GoTo 0 ' You can use this if you want to copy only the values With ActiveSheet.UsedRange .Value = .Value End With mybook.Close savechanges:=False Next Fnum End If CleanUp: Application.ScreenUpdating = True Sheets.Item(1).Select End Sub
Bookmarks