I'm trying to automate a process that where in a folder there are 50+ tsv files. They have to be opened via notepad++ and save it as .txt file in the same folder.
Using the below code i'm opening the tsv file in notepad++.
MyTxtFile = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe I:\Test\Sample.tsv", 1)
However, i have no idea how to save it as txt file by using VBA. Is it doable? If yes kindly teach me how.
Thank you in advance :)
If you only want to rename the files from *.tsv to *.txt you could use the command line
ren *.tsv *.txt
Finally found a remedy by exporting via Data => From Text option the above issue can be tackled..
Below is code for the same..
Do While fname <> ""
Workbooks.Add
Set wBook = ActiveWorkbook
Set wksht = ActiveSheet
With wksht.QueryTables.Add(Connection:="TEXT;" & folder_name & 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
There is another thread which touched upon the general aspect of calling shell commands. Maybe it can be of help to you:
Execute a command in command prompt using excel VBA
Related
I am trying to import data from CSV file "User Roles Entitlements" into my current sheet (current sheet tab name is also "User Roles Entitlements"), which is working perfectly fine if it being imported to cell A1. However, if I try to a table, the code does not work. I know it is a minor tweak, however, I am unable to figure it out.
Note: My file is in the same folder and I am using a variable path import VBA Code.
My code is as follows:
Dim path As String
path = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(ThisWorkbook.path)
Sheets("User Roles Entitlements").Select
Range("A1").Select
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & path & "\User Roles Entitlements.csv", Destination:=Range("A1"))
.Name = "positions_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 857
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Would appreciate if I could get help with this.
Are you okay if the data connection is lost after you import? In other words, will you need to dynamically refresh the table from the CSV file after you bring it in?
If the answer is no, then you can simply convert the range to a ListObject (table) after the fact.
For ease (so you don't have to figure out the range later), you can capture the range from the QueryTable object before you clobber it.
Sub CsvInsert()
Dim sh As Worksheet
Dim qt As QueryTable
Dim r As Range
Set sh = Sheets("User Roles Entitlements")
Set qt = sh.QueryTables.Add(Connection:="TEXT;" & path & _
"\User Roles Entitlements.csv", Destination:=Range("A1"))
With qt
.Name = "positions_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 857
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Then convert the querytable to a range and create a table over the range:
Set r = qt.ResultRange
sh.QueryTables("positions_1").Delete
sh.ListObjects.Add(xlSrcRange, r).Name = "positions_1"
End Sub
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....
I know that this post is going to seem very similar to many other posts to those who understand it. I have learned C++ and C#, both only well enough to do minor work, and I just cannot understand VBA well enough to make this macro happen.
I have just under 100 files that need to be imported to a master file. I cannot modify the source files but the master file needs only select columns.
This macro works almost perfectly I just need the ability to select new file paths for each instance of the macro being used. I have found many posts that seem to use something like this:
https://social.msdn.microsoft.com/Forums/office/en-US/231cbfc5-95ad-4673-a20c-f87355c6bc5e/prompt-user-for-file-name-to-import-as-fixed-width-text-file?forum=exceldev
in order to first make a filepath into a variable and then pass it to the ActiveSheet.QueryTables.Add command. I might just be missing something but there are a lot of variables between all of the examples that I just don't understand. It seems like the msdn page for vba is much less intuitive than those for C#. Either that or I am simply unable to understand them having not taken the babysteps that I need.
Using the macro tool I made the large majority of the code below. About an hour of working allowed me to replace the hardcoded cell with the active cell.
Sub InputDataFromTextFile()
'
' InputDataFromTextFile Macro
'
' Keyboard Shortcut: Ctrl+t
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;E:\Dropbox\College 2016-2017\Research\Buffered Solutions\pH10\With PDADMAC\30.CSV" _
, Destination:=ActiveCell)
.Name = "30"
.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 = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(9, 1, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
I would appreciate any and all help that could be given. Thank you all so much for your time regardless.
So immediately after posting, I hadn't figured it out in the comments I tried something and got it to work. Here is the code as it stands.
Sub InputDataFromTextFile()
Dim Filt As String
Dim FilterIndex As Integer
Dim Title As String
Dim FileName As Variant
' Set up list of file filters
Filt = "All Files (*.*),*.*"
' Display Text Files by default
FilterIndex = 1
' Set the dialog box caption
Title = "Select a File to Import"
' Get the file name
FileName = Application.GetOpenFilename _
(FileFilter:=Filt, _
FilterIndex:=FilterIndex, _
Title:=Title)
' Exit if dialog box is canceled
If FileName = False Then
MsgBox "No file was selected."
Exit Sub
End If
'
' InputDataFromTextFile Macro
'
' Keyboard Shortcut: Ctrl+t
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & FileName, _
Destination:=ActiveCell)
.Name = "30"
.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 = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(9, 1, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
One of my largest issues was honestly that once excel was restarted the Ctrl+T that I had hotkeyed to the command reverted to making a table. I couldn't figure out where it was coming from! Thank you for your help. This saves me a great deal of time.
While the comment made by Parfait about cycling through the files and having them auto import is the next step and a very obviously desired trait in the code, it seems like a lot for me right now. I'm already saving upwards of an hour per mastersheet which is just amazing. Thank you all so much again.
I have an excel file and used this code to import data.
https://www.youtube.com/watch?v=sQIImQbEO_Q
Unlike this example my Datafeeds sheet has data already that is formatted in a particular way. If I rerun the Macro, the existing data shifts to the L1 (That is where the second csv ends) and new data is written from A1.
1) I would like to modify the code to replace the existing one overwrite it.
2) Also the existing one has been formatted in a particular way. I wish to retain the formatting.
How can I best modify my code to do this?
This is the code:
Sub AutomateImport()
For rep = 4 To 16
Dim file_name As String
Dim row_number As String
Dim output_sheet As String
file_name = Sheets("Admin").Range("B" & rep).Value
output_sheet = Sheets("Admin").Range("C" & rep).Value
row_number = Sheets("Admin").Range("D" & rep).Value
Sheets(output_sheet).UsedRange.ClearContents
With Sheets(output_sheet).QueryTables.Add(Connection:="TEXT;" + file_name, Destination:=Sheets(output_sheet).Range("$A$" + row_number))
.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 = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next rep
MsgBox "Done"
End Sub
This function is designed to open a CSV file, and import all the data into a specific Sheet on an Excel Workbook.
But I think there is some kind of problem I can't resolve in some cases with delimiters.
This is my function:
Sub LoopAllExcelFilesInFolder_Invenotry()
Dim strFilename As String
Dim wsMstr As Worksheet: Set wsMstr = ThisWorkbook.Sheets("ALL_ACTIUS")
If MsgBox("Erase sheet before start importing?", vbYesNo, "Delete?") _
= vbYes Then wsMstr.UsedRange.Clear
strFilename = Application.GetOpenFilename _
(FileFilter:="CSV File (*.csv), *.csv", _
Title:="Select CSV file: ")
Worksheets("ALL_MACHINES").Activate
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & strFilename, _
Destination:=Range("A1"))
.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
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
This is part of the source code (CSV file), containing a line that is not beeing "translted" as expected:
Here you can see how this line is translated to the Excel. The 12X5" string should'nt be there. The first column should only contain IP addresses.
I'm pretty sure It's a delimiter character issue, but I can't find the solution.
The Workbooks.Open command worked for me with that issue.
Dim wb As Workbook
strFilename = "yourfilename.csv"
Set wb = Workbooks.Open(Filename:=strFilename, local:=True)