Updated.
I have the following code:
Sub ImportTextFile()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
If Val(Application.Version) > 15 Then
If ActiveWorkbook.AutoSaveOn Then ActiveWorkbook.AutoSaveOn = False
End If
Dim Ret
Dim newWorksheet As Worksheet
Set newWorksheet = Sheets.Add(After:=Sheets("Konvertering"))
Ret = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If Ret <> False Then
With newWorksheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=newWorksheet.Range("$A$1"))
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
newWorksheet.Name = Mid$(Ret, InStrRev(Ret, "\") + 1)
End If
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
It imports a textfile to a new sheet in Excel. How can I update the code so that the new sheet gets the same name as the textfile that was imported?
First, when adding the new worksheet, assign it to an object variable for reference later...
Dim newWorksheet As Worksheet
Set newWorksheet = Sheets.Add(After:=Sheets("Konvertering"))
Then, you can refer to the new worksheet for your query and name your new worksheet as follows...
If Ret <> False Then
With newWorksheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=newWorksheet.Range("$A$1"))
'etc
'
'
End With
newWorksheet.Name = Mid$(Ret, InStrRev(Ret, "\") + 1)
End If
Double InstrRev
You were just another InstrRev away from the solution.
Let's say the path is C:\Test\Input.txt.
After applying InstrRev with \ to Ret ...
x = Mid$(Ret, InStrRev(Ret, "\") + 1)
you got this: Input.txt.
Now you just have to apply InstrRev with . to x ...
FileName = Mid$(x, 1, InStrRev(x, ".") - 1)
to get this: Input.
And now you have to get rid off x i.e. replace x in the second expression with the right side of the first expression to get this:
FileName = Mid$(Mid$(Ret, InStrRev(Ret, "\") + 1), 1, _
InStrRev(Mid$(Ret, InStrRev(Ret, "\") + 1), ".") - 1)
Hence the solution:
Replace this ...
newWorksheet.Name = Mid$(Ret, InStrRev(Ret, "\") + 1)
...with
newWorksheet.Name = Mid$(Mid$(Ret, InStrRev(Ret, "\") + 1), 1, _
InStrRev(Mid$(Ret, InStrRev(Ret, "\") + 1), ".") - 1)
...and you're done.
EDIT:
Links
Workbook.SaveAs
XlFileFormat
The Code
Option Explicit
Sub ImportTextFile()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' The following line is usually written immediately after the previous
' two lines.
On Error GoTo ProgramError
If Val(Application.Version) > 15 Then
If ActiveWorkbook.AutoSaveOn Then ActiveWorkbook.AutoSaveOn = False
End If
Dim Ret As Variant
Dim newWorksheet As Worksheet
Dim ws As Worksheet ' For Each Control Variable
Dim finishSuccess As Boolean
Dim fileName As String
Set newWorksheet = Sheets.Add(After:=Sheets("Konvertering"))
Ret = Application.GetOpenFilename("Text Files (*.txt), *.txt")
' Define fileName
fileName = Mid$(Mid$(Ret, InStrRev(Ret, "\") + 1), 1, _
InStrRev(Mid$(Ret, InStrRev(Ret, "\") + 1), ".") - 1)
' Check if fileName exceeds 31 character limit:
If Len(fileName) > 31 Then GoTo FileNameTooLong
' Check if worksheet name exists.
For Each ws In ThisWorkbook.Worksheets
If ws.Name = fileName Then GoTo WorksheetNameTaken
Next ws
' Import Text File
If Ret = False Then GoTo SafeExit
With newWorksheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=newWorksheet.Range("$A$1"))
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
newWorksheet.Name = fileName
' Stop Excel complaining about losing the code.
Application.DisplayAlerts = False
' Assuming you want to save the file as .xlsx (without code).
ThisWorkbook.SaveAs fileName, xlOpenXMLWorkbook
' If you want to save as .xlsm (with code) then use
' 'xlOpenXMLWorkbookMacroEnabled' and remove the lines
' containing 'Application.DisplayAlerts ...'.
Application.DisplayAlerts = True
' If I'm mmissing the point, just outcomment the previous Application
' block and uncomment the following line and make changes appropriately.
' Thisworkbook.SaveAs fileName, xlOpenXMLWorkbookMacroEnabled
finishSuccess = True
SafeExit:
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
If finishSuccess Then
MsgBox "Finished successfully.", vbInformation, "Success"
' Close workbook without saving changes (False) ensuring that it
' always stays the same. Remove 'False' if I'm missing the point.
ThisWorkbook.Close False
End If
Exit Sub
WorksheetNameTaken:
MsgBox "There is already a worksheet named '" & fileName & "'.", _
vbInformation, "Custom Error Message"
GoTo SafeExit ' or change appropriately.
FileNameTooLong:
MsgBox "The file name '" & fileName & "' exceeds the 31 character limit.", _
vbInformation, "Custom Error Message"
GoTo SafeExit ' or change appropriately.
ProgramError:
' Handle Error (You can do better. A hint: 'vbYesNo'.)
MsgBox "An unexpected error occurred. Error '" & Err.Number & "': " _
& Err.Description, vbCritical, "Custom Error Message"
On Error GoTo 0
GoTo SafeExit ' or change appropriately.
End Sub
Related
I have a code that selects multiple '.csv' files by Application.GetOpenFilename for later importing of these files, but I'd like for all the files in a specific folder to be automatically selected without the user needing to manually selecting them.
This is the section that I'm interested in improving. And below the full code in case something else needs to change.
ChDrive "Q"
ChDir "Q:\TEST\Reports CSV\"
myfiles = Application.GetOpenFilename(FileFilter:="CSV Files (*.csv), *.csv", MultiSelect:=True)
Full code:
Sub ImportMultipleCSV()
Dim myfiles
Dim i As Integer
Dim xSht As Worksheet
Dim ReportsDate As String
ThisWorkbook.Worksheets("Import Data").Range("A3:AV100").ClearContents
With Application
.DisplayAlerts = False
.EnableEvents = False
.ScreenUpdating = False
End With
ChDrive "Q"
ChDir "Q:\TEST\Reports CSV\"
myfiles = Application.GetOpenFilename(FileFilter:="CSV Files (*.csv), *.csv", MultiSelect:=True)
'Import multiple csv in semicolon delimitation
If IsArray(myfiles) Then
For i = LBound(myfiles) To UBound(myfiles)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & myfiles(i), Destination:=Range("A" & Rows.Count).End(xlUp).Offset(1, 0))
.Name = "Sample"
.FieldNames = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 2
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next i
Else
MsgBox "No File Selected"
End If
Dim xConnect As Object
For Each xConnect In ActiveWorkbook.Connections
If xConnect.Name <> "ThisWorkbookDataModel" Then xConnect.Delete
Next xConnect
With Application
.DisplayAlerts = True
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
You can use the Dir function to automatically retrieve all of your CSV files from your folder. Accordingly, your code could be re-written as follows...
Sub ImportMultipleCSV()
With Application
.DisplayAlerts = False
.EnableEvents = False
.ScreenUpdating = False
End With
Dim destWS As Worksheet
Set destWS = ThisWorkbook.Worksheets("Import Data")
destWS.Range("A3:AV100").ClearContents
Dim fileCount As Long
fileCount = 0
Dim myPath As String
myPath = "C:\Users\Domenic\Desktop\" 'change the path accordingly
If Right(myPath, 1) <> "\" Then
myPath = myPath & "\"
End If
'get the first CSV file from the folder
Dim myFile As String
myFile = Dir(myPath & "*.csv", vbNormal)
'loop through each CSV in the folder
While Len(myFile) > 0
'Import multiple csv in semicolon delimitation
With destWS.QueryTables.Add(Connection:= _
"TEXT;" & myPath & myFile, Destination:=destWS.Range("A" & destWS.Rows.Count).End(xlUp).Offset(1, 0))
.Name = myFile
.FieldNames = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 2
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileCommaDelimiter = True
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
fileCount = fileCount + 1
myFile = Dir 'get the next CSV from the folder
Wend
If fileCount > 0 Then
Dim xConnect As Object
For Each xConnect In ActiveWorkbook.Connections
If xConnect.Name <> "ThisWorkbookDataModel" Then xConnect.Delete
Next xConnect
End If
With Application
.DisplayAlerts = True
.EnableEvents = True
.ScreenUpdating = True
End With
MsgBox "Number of files processed: " & fileCount
End Sub
Note that if you're files are in fact delimited by a semi-colon instead of a comma, you'll need to modify the above code by replacing...
.TextFileCommaDelimiter = True
with
.TextFileSemicolonDelimiter = True
I am able to import multiple sheets. Each imported file have 2 columns. I want the first file to be placed on Column A and Column B and the second imported file to be placed on Column C and column D on the same sheet.
The following below is my code to import multiple sheets.
Sub ImportFiles()
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim path As String
Dim filename As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.AllowMultiSelect = True
'Set the initial path to the C:\ drive.
.InitialFileName = ActiveWorkbook.path
'Add a filter that includes the list.
.Filters.Clear
.Filters.Add "Text Files", "*.txt", 1
'The user pressed the button.
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
path = Left(vrtSelectedItem, InStrRev(vrtSelectedItem, "\"))
filename = Right(vrtSelectedItem, Len(vrtSelectedItem) - InStrRev(vrtSelectedItem, "\"))
Call Importfile(path, filename)
Next vrtSelectedItem
Else
End If
End With
Set fd = Nothing
End Sub
Sub Importfile(path As String, filename As String)
'Sheets.Add(After:=Sheets("Sheet1")).Name = "RawData"
'ActiveSheet.Name = filename
On Error Resume Next
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & path & filename, Destination:=Range("$A$1"))
.Name = filename
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlWindows
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileOtherDelimiter = vbTab
.TextFileDecimalSeparator = "."
.TextFileThousandsSeparator = " "
.Refresh BackgroundQuery:=False
End With
End Sub
I did try to place a for loop after "If .Show =-1 Then," such as
Dim FileNames As String
Dim WSNew As Worksheet
For Each filename in FileNames
Set WSNew = ActiveWorkbook.Sheets.Add
Next filename
but it shows an error such that it cant compile it.
Replace your existing procedure with this one:-
Sub Importfile(path As String, filename As String)
Dim Target As Range
Dim C As Long
'Sheets.Add(After:=Sheets("Sheet1")).Name = "RawData"
'ActiveSheet.Name = filename
On Error Resume Next
With ActiveSheet
C = .Cells(1, .Columns.Count).End(xlToLeft).Column
If C > 1 Then C = C + 1
Set Target = .Cells(1, C)
With .QueryTables.Add(Connection:="TEXT;" & path & filename, _
Destination:=Target)
.Name = filename
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = False
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlWindows
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileOtherDelimiter = vbTab
.TextFileDecimalSeparator = "."
.TextFileThousandsSeparator = " "
.Refresh BackgroundQuery:=False
End With
End With
End Sub
Everything remains same as before but the newly imported file will be written to the next free cell in row 1.
I created a pretty good working vba code for importing a csv file from the windows file explorer. However, when I close the explorer before I open a file, a 1004 error dialog pops up. It says the text file to refresh the external range can't be found. The line line at the bottom should be the cause:
.Refresh BackgroundQuery:=False
Does anyone have an idea how to get rid of this error?
Dim ClickCount As Integer
Sub CommandButton1_Click()
Dim sht As Worksheet
Dim LastRow As Long
Dim begin As String
Dim myInput As Long
ClickCount = ClickCount + 1
If ClickCount > 1 Then GoTo Line1 Else GoTo Line2
Line1:
myInput = MsgBox("Gebruikers zijn reeds geimporteerd. Records worden mogelijk dubbel opgeslagen. Wilt u toch doorgaan met importeren?", vbCritical + vbYesNo, "Import error")
If myInput = vbYes Then
GoTo Line2
Else
Exit Sub
Line2:
Set sht = ActiveSheet
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
begin = "$A" & "$" & LastRow + 1
Dim fileName
fileName = Application.GetOpenFilename(FileFilter:="CSV Files (*.csv),*.csv")
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & fileName, _
Destination:=range(begin))
.Name = "User import 1.0"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
End Sub
Dim fileName
fileName = Application.GetOpenFilename(FileFilter:="CSV Files (*.csv),*.csv")
If fileName = False then Exit Sub
I'm used this great resource Import CSV files into Excel, and it was working great last week, but this week i can't get it to work.
What changed?
Sub ImportAllCSV()
Dim FName As Variant, R As Long
R = 1
FName = Dir("*.csv")
Do While FName <> ""
ImportCsvFile FName, ActiveSheet.Cells(R, 1)
R = ActiveSheet.UsedRange.Rows.Count + 1
FName = Dir
Loop
Call KopieraUnikaRaderBlad
Call RaderaLine
Call SammanStall
Call SidforNummer
End Sub
' Sub för att importera csv fil info till blad med namn från filnamnet
Sub ImportCsvFile(FileName As Variant, Position As Range)
Dim newString As String
Dim char As Variant
ActiveWorkbook.Worksheets.Add
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & FileName _
, Destination:=Range("$A$1"))
.Name = "A00-40---1-D02------ Klar_allt"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = ";"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
' det som är in kopierat några kolumner tas bort
Columns("C:I").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
newString = Right(FileName, 25)
'fixar till bladnamnet
For Each char In Split(SpecialCharacters, ",")
newString = Replace(newString, char, "")
Next
ActiveSheet.Name = Left(newString, Len(newString) - 3)
End Sub
This must be Excel "default" location that changed, or you moved the csv files.
You macro Sub ImportAllCSV() will only work if you have files in the current directory.
To be sure, one solution is to use the complete path, e.g.
fName = "C:\local\my_existing_file.csv"
Otherwise, with your formula, FName = Dir("*.csv") calls to the directory Excel considers as "default". This is the directory you have when going to File > Open...
If you want to be sure of current path, then try Re-Initializing "ThisWorkbook.Path", like with the below:
Set CurrWB = Workbooks("the_current_workbook_you_want.xlsm")
directory = currwb.path
FName = Dir(directory & "\*.csv")
This is the answer
Sub ImportAllCSV()
Dim FName As Variant, R As Long
Application.ScreenUpdating = False
R = 1
Set CurrWB = Workbooks("Bok1.xlsm")
directory = CurrWB.Path & "\"
FName = Dir(directory & "*.csv")
Do While FName <> ""
ImportCsvFile FName, ActiveSheet.Cells(R, 1), directory
R = ActiveSheet.UsedRange.Rows.Count + 1
FName = Dir
Loop
Call KopieraUnikaRaderBlad
Call RaderaLine
Call SammanStall
Call SidforNummer
Call KollaFlyttaData
'Call RäknaData
Application.ScreenUpdating = True
End Sub
Sub ImportCsvFile(FileName As Variant, Position As Range, directory As Variant)
Dim newString As String
Dim char As Variant
ActiveWorkbook.Worksheets.Add
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & directory & FileName _
, Destination:=Range("$A$1"))
.Name = "A00-40---1-D02------ Klar_allt" 'vet inte vad den här linjen gör verkar som inget
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = ";"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
.WorkbookConnection.Delete
End With
' det som är in kopierat några kolumner tas bort
Columns("C:I").Select
Selection.Delete Shift:=xlToLeft
Range("A1").Select
newString = Right(FileName, 25)
'fixar till bladnamnet
For Each char In Split(SpecialCharacters, ",")
newString = Replace(newString, char, "")
Next
ActiveSheet.Name = Left(newString, Len(newString) - 3)
End Sub
i would to import the last modified txt file from a directory using a macro in Excel.
I have a folder which is incremented everyday by a new txt file.
The goal is to import the last txt file added in the direrctory.
I've already created a an Excel file with a button affected to macro.
Here is the code of macro:
Sub Import()
'
' Import Macro
' Macro saved on 02/03/2011 by StYellowknife3000
'
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Folder\File_01.txt", Destination:= _
Range("A1"))
.Name = "File_01"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 932
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Thank you
One way to do it is to use the Scripting.FileSystemObject and loop through all the files check their dates. Here's some code I use to open the latest CSV in a folder
For Each fsoFile In fsoFldr.Files
If fsoFile.DateCreated > dtNew And fsoFile.Type = sCSVTYPE Then
sNew = fsoFile.Path
dtNew = fsoFile.DateCreated
End If
Next fsoFile
Workbooks.Open sNew
You can see all the code and the references you need to set here
http://www.dailydoseofexcel.com/archives/2009/05/01/opening-the-newest-file-in-a-folder-with-vba/
I found this example from another thread but it's working only if the filename is always same.
This one check the file with lastmodified but it's not working as i want.
code:
Sub test()
MsgBox FileLastModified("C:\My Documents\abook.xls")
End Sub
Function FileLastModified(strFullFileName As String)
Dim fs As Object, f As Object, s As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(strFullFileName)
s = UCase(strFullFileName) & vbCrLf
s = s & "Last Modified: " & f.DateLastModified
FileLastModified = s
Set fs = Nothing: Set f = Nothing
End Function