All data is stored in text files. I have multiple of these files and I want to import each in a new sheet that bears the name of the file.
I recorded a macro so that it imports the data to the correct specifications. Afterwards, I added the part where it repeats this process for every file in the directory.
The result of my code is that it creates a new sheet with the correct name for each file, but the sheets are empty.
Sub ImportTextfiles()
Dim folderName As String, filePathName As String, FileName As String
folderName = "C:\Users\MyName\Documents\MultipleFiles\"
FileName = Dir(folderName, vbNormal)
While FileName <> ""
filePathName = folderName & FileName
Sheets.Add.Name = FileName
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & filePathName, _
Destination:=Range("$A$1"))
.Name = FileName
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1251
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileFixedColumnWidths = Array(37, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, _
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, _
10, 10, 10, 10, 10)
.TextFileDecimalSeparator = "."
.TextFileThousandsSeparator = ","
End With
FileName = Dir()
Wend
End Sub
You were very close. Recording macros is an excellent way to start learning to script your own custom functions. In this case, you were not using the new worksheet you were adding. So add the new sheet, correctly name it, then use that sheet to import the data.
Option Explicit
Sub ExtDataToSheets()
Dim fnames() As String
Dim fname As Variant
Dim fullpath As String
Dim newSh As Worksheet
fnames = Split("file1.txt,file2.txt,file3.txt", ",")
For Each fname In fnames
fullpath = Application.Path & fname
Set newSh = ActiveWorkbook.Sheets.Add
newSh.Name = fname
With newSh.QueryTables.Add(Connection:="TEXT;C:\Temp\SampleData.csv", _
Destination:=Range("$A$1"))
.Name = "SampleData"
.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, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next fname
End Sub
Related
I Have recoded a code using the Record button.
Basically, I need to remove all special characters using 65001 in File Origin.
I have run a script that converts the .txt in 65001 formats and applies Text to columns as well. Because I need to open .txt data in an excel file
But the problem is the script is run perfectly fine for the 1st TXT file but But for the remaining .txt Text to column function doesn't apply.
Str = "TEXT;" & myFile
With ActiveSheet.QueryTables.Add(Connection:=Str, destination:=Range("$A$1"))
.Name = "UK"
.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
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
I don't know the exact issue. Please find the attahced image as well the formating of 1st and the remainging txt data in excel file.
As you can see in 1st image there is noting after the heading "Letest deleivery date". But for the remain format there are data not perfectly extracted from txt to excel.
Please check and let me know the reason.
Since you're always adding a new querytable, try removing any existing ones first.
Dim Str
Str = "TEXT;C:\Tester\tmp.txt"
'remove any existing querytable(s) and clear associated range
Do While ActiveSheet.QueryTables.Count > 0
With ActiveSheet.QueryTables(1)
Debug.Print "Clearing querytable at ", .ResultRange.Address
.ResultRange.Clear
.Delete
End With
Loop
With ActiveSheet.QueryTables.Add(Connection:=Str, Destination:=Range("$A$1"))
.Name = "UK"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells 'this is better I think
.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
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
I have a slight issue with my VBA macro I get a run time error on this part and I can't figure out where it is, basically the code is meant to open a File Explorer and the user chooses a CSV and then the VBA copies the sheet in a new sheet inside the workbook that has the Macro in it.
Sub manipulate_csv()
Sheets.Add After:=ActiveSheet
csvDatasheetName = "CSV Feed Data"
massagedDatasheetName = "Massaged Data"
objFile = Application.GetOpenFilename(fileFilter:="All Files(* . *) , * . * ") ' choose load path'
connectionText = "TEXT;" & objFile
With ActiveSheet.QueryTables.Add(Connection:= _
connectionText, Destination:= _
Range("$A$1"))
.Name = "TestCSV"
.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 = True
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileCommaDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End with
End sub
If you have any idea what is causing my issue, I would be very thankful, to help me solve it.
Best regards
Hi there I am trying to import a text file from a folder based on FileDialog from a set path? I have a code that imports a text file but it only opens up a generic C:\\ path, How should I modify the code below in order to open a folder for a specified path?
Sub ImportTextFile()
Dim fName As String, LastRow As Long
fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fName = "False" Then Exit Sub
LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
Destination:=Range("A" & LastRow))
.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 = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierNone
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "" & Chr(10) & ""
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Any help would be greatly appreciated!
I did the following alteration to the beginning of the code, but now I get "1004 Application Defined Error"
Sub ImportTextFile()
Dim fName As FileDialog, LastRow As Long
Set fName = Application.FileDialog(msoFileDialogOpen)
fName.InitialFileName = "\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Pointsec for PC Web RH\2017\"
If fName = "False" Then Exit Sub
Using ChDir before opening the file might help. I would comment, but don't have enough reputation so posting here.
e.g.
Sub ImportTextFile()
ChDir "C:/yourpath/folder/etc"
Dim fName As String, LastRow As Long
....
I'm trying to make a macro that could import *txt files from a folder and I did it. Now I'm stuck on this:
I need to name the worksheets with the same name as the *txt file. The actual code is importing as default names for new worksheets.
Sub ImportTXT()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("A:\REPORTS\2017\*.txt")
Do While strFile <> vbNullString
Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "A:\REPORTS\2017\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.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 = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 4, 9)
.TextFileFixedColumnWidths = Array(14, 10, 6, 11, 43, 15, 33, 14, 1, 14, 16, 4, 13, 11, _
11, 10)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End Sub
Add a line of code after the add line
Set ws = Sheets.Add
ws.Name = strFile
With ws.QueryTables.Add(...
After "End With", try that:
Set ws = ThisWorkbook.ActiveSheet
ws.Name = Left(srtFile, Len(srtFile) - Len(".txt"))
srtFile = Dir
Final code:
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("A:\REPORTS\2017\*.txt")
Do While strFile <> vbNullString
Set ws = Sheets.Add
ws.Name = strFile
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "A:\REPORTS\2017\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.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 = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 4, 4, 9)
.TextFileFixedColumnWidths = Array(14, 10, 6, 11, 43, 15, 33, 14, 1, 14, 16, 4, 13, 11, _
11, 10)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End Sub
I am trying to open a file from a user specified path using a VBA Function.
When I paste the content of the file to the desired worksheet, it pastes some weird unrecognizable characters in the worksheet. Can anyone figure out what am I doing wrong?
Here is my code:
Sub x_Macro()
'****************Declaring relevant variables****************'
Dim t As Range
Dim path: path = Application.GetOpenFilename("XLS Files (*.xls), *.xls")
Dim cht1 As ChartObject
'Dim button_click As VbMsgBoxResult
Application.ScreenUpdating = False
Sheets(2).Activate
If path = False Then Exit Sub
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & path, Destination:=Range("A1"))
.FieldNames = True
.RowNumbers = True
.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 = True
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With