This is my first question here, I have a macro to import .txt files "Semicolon" delimited into Excel. Each file is name specific, and each file is imported in a new sheet. But if one of theses files doesn't exists, the macro Fails. I want to add an "On Erro" to handle these cases, if the file doesn't exists, skip it. Heres the code:
Sub Importar_Dep()
Dim Caminho As String
Caminho = Sheets("DADOS").Cells(5, 8).Value
Sheets("DEP").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Caminho, _
Destination:=Range("$A$1"))
.Name = "RECONQUISTA_DEP_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 = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Here is your code with the check if the file exist:
Sub Importar_Dep()
Dim Caminho As String
Caminho = Sheets("DADOS").Cells(5, 8).Value
Sheets("DEP").Select
'+++++ Added block to check if file exists +++++
Dim FS
Set FS = CreateObject("Scripting.FileSystemObject")
Dim TextFile_FullPath As String
'The textfile_fullPath should be like:
TextFile_FullPath = "C:\Users\Username\Desktop\" & _
RECONQUISTA_DEP_0 & _
".txt"
If FS.FileExists(TextFile_FullPath) Then
'++++++++++++++++++++++++++++++++++++++++++++++++
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Caminho, _
Destination:=Range("$A$1"))
.Name = "RECONQUISTA_DEP_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 = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
End Sub
Like in your comment, if you want to run through all files that have a certain name in common (a filter), you can use this code. The above modifications have then became useless because with this you don't have to check if file exists anymore since it will just go through all existing files. You could have to check if the folder exists though:
Sub RunThroughAllFiles()
Dim Caminho As String
Caminho = Sheets("DADOS").Cells(5, 8).Value
Sheets("DEP").Select
Dim FS
Set FS = CreateObject("Scripting.FileSystemObject")
Dim Filter As String: Filter = "RECONQUISTA_DEP_*.txt"
Dim dirTmp As String
If FS.FolderExists(Caminho) Then
dirTmp = Dir(Caminho & "\" & Filter)
Do While Len(dirTmp) > 0
Call Importar_Dep(Caminho & "\" & dirTmp, _
Left(dirTmp, InStrRev(dirTmp, ".") - 1))
dirTmp = Dir
Loop
Else
MsgBox "Folder """ & Caminho & """ does not exists", vbExclamation
End If
End Sub
Sub Importar_Dep(iFullFilePath As String, iFileNameWithoutExtension)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & iFullFilePath, _
Destination:=Range("$A$1"))
.Name = iFileNameWithoutExtension
.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 = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
For more information see Dir, FileExists and FolderExists
Here:
Sub Abrir_PORT()
Dim Caminho As String
Caminho = Sheets("DADOS").Cells(5, 5).Value
Sheets("PORT").Select
Dim FS
Set FS = CreateObject("Scripting.FileSystemObject")
Dim Filter As String: Filter = "ATENTO_TLMKT_REC*.txt"
Dim dirTmp As String
If FS.FolderExists(Caminho) Then
dirTmp = Dir(Caminho & "\" & Filter)
Do While Len(dirTmp) > 0
Call Importar_PORT(Caminho & "\" & dirTmp, _
Left(dirTmp, InStrRev(dirTmp, ".") - 1))
dirTmp = Dir
Loop
End If
End Sub
Sub Importar_PORT(iFullFilePath As String, iFileNameWithoutExtension)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & iFullFilePath, _
Destination:=Range("$A$1"))
.Name = iFileNameWithoutExtension
.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 = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
iRow = 2
Do While Sheets("PORT").Cells(iRow, 1) <> ""
If Cells(iRow, 2) = IsNumber Then
Else
Rows(iRow).Select
Selection.EntireRow.Delete
iRow = iRow - 1
contagem = contagem + 1
End If
iRow = iRow + 1
Loop
End With
End Sub
Related
I am working to create a VBA/macro that imports 2 CSV files from a specific folder into 2 worksheets in an Excel template that I have created.
To be more specific, these files are created and saved as new workbooks on a daily basis (two new files being added into the folder everyday) so my problem is how to code my macro to always import the 2 latest files?
Please see below the code from which I manually select and import the latest files using macro. However, re-running the macro does not work as it shows "run-time error '5' - invalid procedure call or argument". Your help would be much appreciated.
Sub Macro1()
'
' Macro1 Macro
' IMPORT CSV FILES
'
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_AM 19-01-2018 3-15-03 AM.csv" _
, Destination:=Range("$A$1"))
.CommandType = 0
.Name = "AP_PDP_VehicleLoad_Report_AM 19-01-2018 3-15-03 AM"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Sheets.Add After:=ActiveSheet
Application.CutCopyMode = False
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_PM 19-01-2018 7-15-02 PM.csv" _
, Destination:=Range("$A$1"))
.CommandType = 0
.Name = "AP_PDP_VehicleLoad_Report_PM 19-01-2018 7-15-02 PM"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Sheets("Sheet1").Select
Columns("A:N").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1").Select
Sheets("Sheet2").Select
Columns("A:N").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1").Select
Sheets("Sheet2").Select
Sheets("Sheet2").Name = "PM"
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "AM"
Sheets("AM").Select
End Sub
You can find the latest file(s) this way:
EDIT: Dir return only the filename, so you need to append the path, too.
EDIT2: As per user request a few Debug.Print is inserted.
Sub main()
Dim s1 as String, s2 as String
s1 = LastFile("P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_AM")
Debug.Print "Last file1: " & s1
s2 = LastFile("P:\APS\Reports_From_PDP\AP_PDP_VehicleLoad_Report_PM")
Debug.Print "Last file2: " & s2
End Sub
Function LastFile(sName as String) as String
Dim dLatest as Date
Dim dFound as Date ' date of one matching filename
Dim sLatest as string ' the latest file or ""
Dim sFound as string ' one matching filename
Dim sPath as string
dLatest = 0
sLatest = vbnullstring
sPath = Left$(sName, InStrRev(sName, "\"))
sFound = Dir(sName & "*.csv")
Do While sFound <> vbnullstring
Debug.Print "Found: " & sFound
dFound = FileDateTime(sPath & sFound)
If dFound > dLatest Then
dLatest = dFound
sLatest = sFound
Endif
sFound = Dir
Loop
LastFile = sLatest
End Function
I need to import my data into another Excel sheet instead of active worksheet.
I have 2 sheets the UI and the DATA_List. My button is in the UI. I want to import the csv file to data_list sheet.
Sub btnImport_Click()
Dim slect As String
Set r = Range("A" & Cells(Rows.Count, "A").End(xlUp).Row + 1)
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
Exit Sub
End If
slect = .SelectedItems(1)
End With
With ThisWorkbook.Sheets("UI").QueryTables.Add(Connection:= _
"TEXT;" & slect, Destination:=r)
.Name = "Data"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Change the first line to
Set r = Worksheets("data_list").Range("A1")
You will also need to change the line
With ThisWorkbook.Sheets("UI").QueryTables.Add(Connection:= _
"TEXT;" & slect, Destination:=r)
To
With ThisWorkbook.Sheets("data_list").QueryTables.Add(Connection:= _
"TEXT;" & slect, Destination:=r)
I'm trying to convert tsv files in a folder to xlsx format by importing them as text file using Data=>From Text option via VBA.
During that encountered this error
Code:
Sub convert()
Dim CSVfolder As String, XlsFolder As String, fname As String, wBook As Workbook
CSVfolder = ActiveSheet.Range("B2").Value & "\"
fname = Dir(CSVfolder & "*.tsv")
Do While fname <> ""
Workbooks.Add
Set wBook = ActiveWorkbook
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fname, Destination:=Range("$A$1"))
.Name = fname
.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 = xlTextQualifierNone
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
wBook.Close False
fname = Dir
Loop
End Sub
End Sub
Why i'm getting the error in .Refresh BackgroundQuery:=False ?
The error is happening there as it's at the Refresh stage that it looks for the file.
The issue is that Fname won't contain the path.
Change your connection to:
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & CSVfolder & fname, Destination....
"This code can open source file with any path .. but now I have the list of source path files on sheet1 and I want to open the file on active cell.. How should I fix this code ? "
Dim Ret
Ret = Application.GetOpenFilename("All Files (*), *")
Sheet2.Activate
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
Assign the value of the ActiveCell to Ret.
Ret = ActiveCell.Value
Then check if the returned path is valid. Something like:
If Dir(Ret) <> "" Then
'~~> rest of your code here
Else
MsgBox "Invalid Path"
'~~> or do something else
End If
HTH.
I have this vba code below that was generated by the macro recorder. It imports a csv file into the current excel sheet with some specific column settings. Right now the path to the csv file is hard coded to "C:\Users\myuser\Desktop\logexportdata.csv". How can I change this so that there is a dialog prompt that asks the user to find the .csv file for import?
Sub Import_log()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\myuser\Desktop\logexportdata.csv", Destination:=Range( _
"$A$2"))
.Name = "logexportdata"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 2
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(5, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
try this:
Sub Import_log()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & getFile, Destination:=Range( _
"$A$2"))
.Name = "logexportdata"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 2
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(5, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Function GetFile() As String
Dim filename__path As Variant
filename__path = Application.GetOpenFilename(FileFilter:="Csv (*.CSV), *.CSV", Title:="Select File To Be Opened")
If filename__path = False Then Exit Function
GetFile = filename__path
End Function