Text To Columns isn't working in my vba script - excel

I am trying to get my Text To Columns to work in my VBA script, but it's not working for me.
I understand how it works in excel and even used the macro record to get it working, but when adding it to my script nothing happens. I even looked at online forums. What I'm doing is extracting data from one workbook to the other and the data that I am getting needs to be converted to Text To Columns once the data is transferred to the other workbook.
I have two separate Sub functions that I used below: Neither of them worked. One of them is from the macro record and the other I found online.
Code from Macro Record below:
Sub TextToCol()
Selection.TextToColumns Destination:=Range("D3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, OtherChar _
:="" & Chr(10) & "", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), _
TrailingMinusNumbers:=True
End Sub
Code from online forum below:
Sub TextToCol()
Selection.Range("D3:D8").TextToColumns _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=True, _
Space:=True
End Sub
The code below is what I am using to connect to source workbook:
'Save Above Created New Workbook
sWorkbook.SaveAs Filename:="C:\Users\username\Desktop\fileName\Test.xlsx"
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
Set OpenBook = Application.Workbooks.Open(FileToOpen)
Below is the code to send data to the destination workbook:
Workbooks("Test.xlsx").Worksheets("Sheet1").Range("D" & counter).value = dataThatWasExtracted
What am I doing wrong?

Related

How do I get the text from a .txt file and write it in a new sheet in the same excel file

I want a whole text file to enter into a new sheet in excel. Right now I am only getting all values in to one cell, I want it to look like in the text file. Like every row get one row in excel.
I have tried this tutorial but this doesn't get it.
https://www.excel-easy.com/vba/examples/read-data-from-text-file.html
I solved it for you who wants to know how check below
Sub GetText()
Dim SheetName As String
Dim TMPWorkBook As Workbook
Dim FilePath As String
Dim TxtFilePath As String
Dim TxtFileName As String
Set WB = ThisWorkbook
SheetName = "Test_Result"
TxtFileName = "C:\getitdone.txt"
Workbooks.OpenText Filename:= _
TxtFileName _
, Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo:=Array(Array(1, 1), _
Array(2, 1)), DecimalSeparator:=".", ThousandsSeparator:=",", _
TrailingMinusNumbers:=True
Set TMPWorkBook = ActiveWorkbook
Cells.Select
Selection.Copy
Workbooks("Getitdone.xlsm").Activate
Sheets.Add.Name = "Data"
Range("A1").PasteSpecial xlPasteValues
End Sub

using copy destination vba between workbooks

Been working a project using recorded macros to complete copying and pasting between workbooks. Recorded macros has been working BUT, when reading the forums people are stating copy/paste method takes more time for macro to run and is very inefficient. So I'm trying to sound out a copy destination vba line that would copy several columns starting from Range(A2:G2000) and then paste to range area starting at (B6:H2000). I'm not good at this and trying to learn more efficiency. Two things here come to mind. A simple copy and paste method which I have working. BUT would utilize the straight source = destination. Could this be done? After reading this you may see another issue. Why have down to Row 2000 selected and copy/pasted? You are correct in your thinking. Some reports(txt files) have 100 rows, some 300, none more than 1000 but I'm overdoing the copy selection because I'm won't be sure about future txt files. I was thinking if you could just select the column down to the last row used would be cool. This is way beyond me. I'd be happy just a new way to copy/paste efficiently.
I would appreciate any help that anyone could offer. let me know what you think.
Thanks
Boomer
enter code here
Sub import_data()
'
'
'import_data
'
Application.ScreenUpdating = False
'
'Opens the txt file in excel - text delimited and leaves file open until
we close at bottom of code. There is no 'name for this workbook.
Workbooks.OpenText (Module33.FileDir + "\cf_data.txt"), Origin:=437, _
StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1),
_
Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1)),
TrailingMinusNumbers:=True
'The line below is where I'm selecting data from the current opened
workbook and copying to another workbook
ActiveWindow.Sheet1.Range("A2:G2000").Copy
Destination:=Workbooks("Auto_Data.xlsm").Sheet2.Range ("B6:H2000")
'This info below is a (recorded marco). All works if I rem out the above
line and open up all the below lines
' Range("A2:G2000").Select
' Selection.Copy
' Windows("Auto_Data.xlsm").Activate
' Sheet2.Select
' Range("B6:H6").Select
' ActiveSheet.Paste
' Selection.AutoFilter
' Application.CutCopyMode = False
' ActiveWindow.ActivateNext
' ActiveWindow.Close
' Range("B4").Select
Application.ScreenUpdating = True
End Sub
A direct value transfer is typically faster than a copy and uses less memory since it doesn't involve the clipboard.
Sub import_data()
dim lr as long, arr as variant
dim wb1 as workbook
set wb1 = Workbooks.OpenText(filename:=Module33.FileDir & "\cf_data.txt"), Origin:=437, _
StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False, _
Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), _
Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1)),
TrailingMinusNumbers:=True)
with wb1.sheets(1)
lr = .range("A:G").Find(what:="*", after:=.range("A1"), searchorder:=xlbyrows, _
searchdirection:=xlprevious).row
.range(.cells(2, "A"), .cells(lr, "G")).value
end with
wb1.close
Workbooks("Auto_Data.xlsm").Sheet2.Range("B6").resize(ubound(arr, 1), ubound(arr, 2)) = arr
end sub

XLSB Personal Macro file Variable Error

Disclaimer: This is not my code. I took a macro from a regular xlsm file and placed it on a xslb file to have it handy for analysis. The macro works correctly in the xlsm, but encounters a variable issue on the xlsb file.
ColumnToFormat identifies a specific column. I verified that the column is present within the worksheet on my Locals window.
Main Sub
ColumnToFormat = Application.WorksheetFunction.Match("OR_TR_OLD_BAL", ActiveSheet.Rows(1), False)
Call FormatAmounts
When I start running FormatAmounts, however, the variable disappears and Excel throws a RunTime Error 1004; Application Defined or Object Defined Error. When testing the xlsm file, this does not happen. The variable gets passed from the main sub to the helper sub. See FormatAmounts sub below.
Sub FormatAmounts()
ActiveSheet.Columns(ColumnToFormat).Select
Selection.TextToColumns Destination:=Range(ActiveSheet.Columns(ColumnToFormat).Address), DataType:= _
xlDelimited, TextQualifier:=xlNone, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:= _
False, FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
Selection.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(#_)"
End Sub
Pass the ColumnToFormat value over to the sub procedure and add error control in the main sub by using Application.Match to a variant and testing the variant for error.
sub main()
dim ColumnToFormat as variant
ColumnToFormat = Application.Match("OR_TR_OLD_BAL", ActiveSheet.Rows(1), 0)
if not iserror(ColumnToFormat ) then FormatAmounts clng(ColumnToFormat)
end sub
Sub FormatAmounts(c as long)
with ActiveSheet.Columns(c)
.TextToColumns Destination:=.cells(1), DataType:=xlDelimited, TextQualifier:=xlNone, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=False, _
FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
.NumberFormat = "_(* #,##0.00_);_(* (#,##0.00);_(* ""-""??_);_(#_)"
end with
End Sub

VBA code help opening file with differnt name

I have a Macro i made and can't seem to get it to work correctly.
If i run the macro and pick a file in a folder with multiple files of the same type.
it only opens the first file in the folder. know matter what file i try to open, it will re-open the same file. for example. if i have 3 files with the names
cycle0001 , cycle0002, cycle0003 when ever i try to open file 003 it opens file 001 always. the code works great except i can't open the file i would like.
only the file with the lowest number in the name.
Here is my code.
Sub jsonDataExtractor()
'
' jsonDataExtractor Macro
' Json Data Extractor
'
' Keyboard Shortcut: Ctrl+t
'
File = Application.GetOpenFilename( _
FileFilter:=" (*.json), *.json", _
Title:="Select a file or files", _
MultiSelect:=True)
Application.ScreenUpdating = False
Workbooks.OpenText filename:= _
"cycle*.json", StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=True, Comma:=True, _
Space:=False, Other:=True, OtherChar:=":", FieldInfo:=Array(Array(1, 9), _
Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
Use code similar to this:
Option Explicit
Sub jsonDataExtractor()
Dim selectedFile As Variant, itm As Variant
selectedFile = Application.GetOpenFilename(FileFilter:=" (*.json), *.json", _
Title:="Select a file or files", _
MultiSelect:=True)
Application.ScreenUpdating = False
If TypeName(selectedFile) <> "Boolean" Then
For Each itm In selectedFile
Workbooks.OpenText Filename:=itm, StartRow:=1, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=True, _
Tab:=True, Semicolon:=True, Comma:=True, _
Space:=False, Other:=True, OtherChar:=":", _
FieldInfo:=Array(Array(1, 9), _
Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True
Next
End If
Application.ScreenUpdating = True
End Sub
.
You need to use the result returned by Application.GetOpenFilename()
.
If MultiSelect:=True it can return either
a Boolean (False if the user canceled)
or an array of variants (file names) even if the user selects only one file
.
If MultiSelect:=False it can return either
a Boolean (False if the user canceled)
or the file name (including its full path)

How to open and extract information from multiple files in VBA

I have around 30 files that I want to perform the same analysis on. Ideally, I want VBA to open all files and extract a certain (identical) piece of information. However, I don't know how to write a function for it. I was thinking of saving all the files as CSV and importing to python (a language I'm familiar with) which would make it easier for my data analysis. The reason I'm importing into excel is because python has difficulty reading .TX0 files (parsing line by line would be time consuming).
This is what i Have for the csv conversion. How do i translate this into the extraction of multiple files?
Sub TX0_CSV()
'
' TX0_CSV Macro
'
'
Workbooks.OpenText Filename:="X/.....fid002.TX0", Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), _
Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
Range("A1:O13").Select
Range("O13").Activate
Selection.ClearContents
Rows("15:16").Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=9
Range("A20:H29").Select
Range("H29").Activate
Selection.ClearContents
Range("J19").Select
ActiveWorkbook.SaveAs Filename:="X:\Joey\FID002.csv", FileFormat:=xlCSV, _
CreateBackup:=False
End Sub
You could convert it to a sub and then repeatedly call it.
Here is an example (Untested) Also note how we got rid of .Activate and .Select. You may want to see This
Sub ConvertFile(flName As String, newFileName As String)
Dim wb As Workbook
Dim ws As Worksheet
Workbooks.OpenText Filename:=flName, Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), _
Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
Set wb = ActiveWorkbook
Set ws = wb.Sheets(1)
With ws
.Range("A1:O13").ClearContents
.Rows("15:16").Delete Shift:=xlUp
.Range("A20:H29").ClearContents
End With
wb.SaveAs Filename:=newFileName, FileFormat:=xlCSV
wb.Close (False)
End Sub
Example
Sub Sample()
ConvertFile "C:\Test1.dat", "C:\Test2.dat"
End Sub

Resources