How to save as .txt in vba - excel

I am looking to have my Macro save a new sheet that i created as a .txt file. this is the code i have so far.
Sub Move()
'
' Move Macro
'
' Keyboard Shortcut: Ctrl+m
'
Sheets("Sheet1").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:="e:" & _
"HDR" + Format(Now(), "YYYYMMDDhhmmss") & ".txt"
End Sub
That includes my macro. I am having trouble with the last part where it saves as a .txt file.
I am currently getting a bunch of crap on my .txt file, here is an example,
"PK ! !}ñU{ Š [Content_Types].xml ¢(  ÌTÝNÂ0¾7ñ–Þš­€‰1†Á…⥒ˆPÚ3¶ÐµMOÁñöž•Ÿ¨".
Any help would be great.

Manually changing the extension of the file name does not actually change the file type. The SaveAs method takes a file type argument. The code you want is
ActiveWorkbook.SaveAs Filename:="e:" & "HDR" + Format(Now(), "YYYYMMDDhhmmss") _
& ".txt", FileFormat:= xlTextWindows
Doing a search from within Excel help for XlFileFormat will get you (almost) the full list of possible file formats, including 6 text formats, and 4 CSV formats.

Adding txt to the name does not automatically encode the word document into plain text format.
Instead attempt
ActiveWorkbook.SaveAs Filename:="e:" & _
"HDR" + Format(Now(), "YYYYMMDDhhmmss") & ".txt", FileFormat:=wdFormatText, Encoding:=1252

The ActiveWorkbook.SaveAs method adds double quote to the beginning and end of every line in the file.
This method parses each line from a given range and transforms it into a CSV file:
Sub SaveSheetToCSVorTXT()
Dim xFileName As Variant
Dim rng As Range
Dim DelimChar As String
DelimChar = "," 'The delimitation character to be used in the saved file. This will be used to separate cells in the same row
xFileName = Application.GetSaveAsFilename(ActiveSheet.Name, "CSV File (*.csv), *.csv, Text File (*.txt), *.txt")
If xFileName = False Then Exit Sub
If Dir(xFileName) <> "" Then
If MsgBox("File '" & xFileName & "' already existe. Overwrite?", vbYesNo + vbExclamation) <> vbYes Then Exit Sub
Kill xFileName
End If
Open xFileName For Output As #1
'Save range contents. Examples of ranges:
'Set rng = Activesheet.Range("A1:D4") 'A rectangle between 2 cells
'Set rng = Activesheet.columns(1) 'An entire column
Set rng = ActiveSheet.Range("B14").CurrentRegion 'The "region" from a cell. This is the same as pressing CTRL+T on the selected cell
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
lineText = IIf(j = 1, "", lineText & DelimChar) & rng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
MsgBox "File saved!"
End Sub

Related

Export to Text without Quotation Marks

I have multiple worksheets in my workbook.
Each worksheet has two columns of data (ColA and ColC) which I want to print to separate text files.
The attached code results in two text files: “WorksheetTab_LnFn.txt” and “WorksheetTab_FnLn.txt”
The text file saved from my ColA does NOT quotations whilst the second text file saved from my ColC DOES HAVE quotation marks - I want each resulting text file to NOT have quotation marks.
I may have worksheets later with data in ColA, ColC, ColE and ColG, each of which I want to export/save/print to a text file – thus I would want in that case four separate text document, all WITHOUT quotation marks.
The best code I have been able to find is locate is: Write export of selected cells as a .txt file without "quotation marks" and I have looked at How to create a text file using excel VBA without having double quotation marks?.
I understand most of it, but am not being successful at integrating parts of this code into mine. Ideally I am seeking to reduce the code and loop so it would process ColA and then ColB without having two separate code blocks. I did use code I found and made minimal changes, but do not know if the Case LCase line is necessary
'Create FirstName LastName Isolation TXT files
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each sh In Sheets
Select Case LCase(sh.Name)
Case LCase("[COLOR=#0000ff]Master[/COLOR]"), LCase("[COLOR=#0000ff]Info[/COLOR]")
Case Else
sh.Range("A:A").Copy
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\" & sh.Name & "_FnLn.txt", _
FileFormat:=xlTextMSDOS, CreateBackup:=False
ActiveWorkbook.Close False
End Select
Next
'Create LastName FirstName Isolation TXT files
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each sh In Sheets
Select Case LCase(sh.Name)
Case LCase("[COLOR=#0000ff]Master[/COLOR]"), LCase("[COLOR=#0000ff]Info[/COLOR]")
Case Else
sh.Range("C:C").Copy
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\" & sh.Name & "_LnFn.txt", _
FileFormat:=xlTextMSDOS, CreateBackup:=False
ActiveWorkbook.Close False
End Select
Next
MsgBox "Text Files Created"
End Sub
This should do what you want:
Sub Tester()
Dim filename As String, myrng As Range, sh As Worksheet, wb As Workbook
Set wb = ThisWorkbook
For Each sh In wb.Worksheets
filename = wb.Path & "\" & sh.Name & "_FnLn.txt"
Set myrng = sh.Range("C1:C" & sh.Cells(sh.Rows.Count, "C").End(xlUp).Row) 'use sh reference
RangeToTextFile myrng, filename 'comma-separated
'RangeToTextFile myrng, filename, vbtab 'e.g. for tab-separated file
Next
MsgBox "Text Files Created"
End Sub
'write a range `rng` to a text file at `fPath`. Default separator is comma
Sub RangeToTextFile(rng As Range, fPath As String, Optional separator As String = ",")
Dim data, r As Long, c As Long, sep, lo As String, ff As Integer
ff = FreeFile() 'safer than using hard-coded #1
Open fPath For Output As #ff
If rng.Cells.CountLarge = 1 Then
ReDim data(1 To 1, 1 To 1) 'handle special case of single cell
data(1, 1) = rng.Value
Else
data = rng.Value 'get all values as an array
End If
For r = 1 To UBound(data, 1) 'loop rows
lo = "" 'clear line output
sep = "" 'clear separator
For c = 1 To UBound(data, 2) 'loop columns
lo = lo & sep & data(r, c) 'build the line to be written
sep = separator 'add separator after first value
Next c
Print #ff, lo 'write the line
Next r
Close #ff
End Sub

My VBA code worked in excel 2010 but does not in excel 2019

I have a code (seen below at the bottom of this message) built by someone else and it has worked very well in excel 2010 but our administration migrated us to excel 2019. Now the same code produces errors. I have also tried checking if there were new add-ins or references in the reference library in vba but have not found anything that removes the errors or allows the code to execute properly.
The function of the code is basically like this:
The code is linked to a pivot table in a worksheet in a workbook. It will ask the user a few questions such as is this a 'RFQ' and then a msg box will open for them to enter a file name. It then asks the user if they wish to have the data added to another worksheet in the same workbook. After all these are answered the code should open an new workbook and copy/paste over data from a hidden worksheet from the original workbook into this new workbook. This new workbook should become the focus and allow the user to make any other changes before they save and close it.
The code automatically saved the new workbook in a location (using a HLink) that is referenced from a cell on another hidden worksheet in the original workbook.
The errors that take place now is this: "The following features cannot be saved in macro-free workbooks: VB Project To save a file with these features, click No, and then choose a macro-enabled file type in the File type list. To continue saving as a macro-free workbook, click Yes.
If the user says yes, the it says the new workbook that was just created 'already exists in this location. Do you want to replace it?"
If you say yes, everything goes blank and you have to restart excel. If you say no, the vba debugger opens to the end of the code highlighting the last part of the code:
ActiveWorkbook.SaveAs FileName:=HLink _ , FileFormat:"xlOpenXMLWorkbook, CreateBackup:=False
I have tried changing some sections of the code. From this:
`'Save
On Error GoTo ErrFileClose:
HLink = (FilePath & "\" & FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx")
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If`
To this:
'Save
On Error GoTo ErrFileClose:
HLink = (FilePath & "\" & FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#"))
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=51, CreateBackup:=False
End If
And similarly, from this:
'Check if previously created file is open and close it so new one can be saved
ErrFileClose:
FinalFileName = FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx"
Workbooks(FinalFileName).Close SaveChanges:=True
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
To this:
'Check if previously created file is open and close it so new one can be saved
ErrFileClose:
FinalFileName = FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#")
Workbooks(FinalFileName).Close SaveChanges:=True
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=51, CreateBackup:=False
These changes sometimes help and seem to remove the vb project error but it is not consistent every time I run the macro.
Any help is appreciated as we cannot move forward using this as it stands.
Thanks.
Sub ImportFile()
'
' ImportFile Macro
Call UnprotectAll
'Create Import
Dim curWorkbook As Workbook
Dim ReqType As String
Dim FileName As String
Dim FinalFileName As String
Dim FilePath As String
FilePath = Sheets("X").Range("C3").Value
Dim HLink As String
Application.ScreenUpdating = False
Sheets("Import").Visible = True
Sheets("Import").Copy
ActiveSheet.Unprotect
'Edit import to remove formulas and blank rows
Range("A1:AC500").Value = Range("A1:AC500").Value
Columns("C:C").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Set curWorkbook = ActiveWorkbook
Windows("Transactions.xlsm").Activate
Sheets("Import").Visible = False
curWorkbook.Activate
'Save Import
ReqType = MsgBox("Click YES if you are creating an RFQ", vbYesNoCancel)
'vbCancel = 2, vbYes = 6, vbNo = 7
If ReqType = 6 Then
ReqType = "RFQ"
Else
If ReqType = 7 Then
ReqType = "Ordered"
Else
Exit Sub
End If
End If
FileName = InputBox("Please enter the Incident number or other Unique ID Number to save this file as:")
'Cancel Save
If FileName = "" Then
ActiveWorkbook.Close SaveChanges:=False
Call ProtectAll
Application.ScreenUpdating = True
MsgBox ("File Not Created")
Exit Sub
Else
'Save
On Error GoTo ErrFileClose:
HLink = (FilePath & "\" & FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx")
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If
'Add Order to Receive tab ?
If MsgBox("Ok to add this data as Transaction: " & ReqType & "?", vbOKCancel) = vbOK Then
Windows("Transactions.xlsm").Activate
Else
'Do Not add Order to transactions Order - Receipt
ActiveWorkbook.Close SaveChanges:=False
Call ProtectAll
Application.ScreenUpdating = True
MsgBox ("This has not been added as a transaction. Click the HuB button when ready to try again. A new import file will be created and can be saved over the one just created.")
Exit Sub
End If
'AddOrder to Transactions Order - Receipt
ActiveSheet.PivotTables("ToBeOrderedPivot").RowRange.Select
'Remove headers and column 1
Selection.Offset(1, 1).Resize(Selection.Rows.Count - 1, _
Selection.Columns.Count).Select
'Remove Extra Columns
Dim FirstRow As Integer
Dim LastRow As Integer
FirstRow = Selection.Row
LastRow = FirstRow + Selection.Rows.Count - 1
Range("C" & FirstRow & ":F" & LastRow & ",AA" & FirstRow & ":AA" & LastRow & ",L" & FirstRow & ":L" & LastRow).Select
Selection.SpecialCells(xlCellTypeVisible).Copy
'Move to end of Orders table
Sheets("Receive").Select
Count = Range("Orders[Mtl ID]").Rows.Count
Range("B" & Count + 4).Select
'Paste Values
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
'Set Values
Selection.Offset(0, 8).Columns(1).Value = Selection.Offset(0, 2).Columns(1).Value
If ReqType = "RFQ" Then
Selection.Offset(0, 2).Columns(1).Value = 0
Selection.Offset(0, 7).Columns(1).Value = ReqType
Else: Selection.Offset(0, 2).Columns(1).Value = Selection.Offset(0, 5).Columns(1).Value
End If
Selection.Offset(0, 5).Columns(1).Value = Selection.Offset(0, 3).Columns(1).Value
Selection.Offset(0, 3).Columns(1).Value = Selection.Offset(0, 4).Columns(1).Value
Selection.Offset(0, 4).Columns(1).Value = Selection.Offset(0, 8).Columns(1).Value
Selection.Offset(0, 8).Columns(1).Value = FileName
Selection.Offset(0, 9).Columns(1).Value = Format(Date, "[$-409]yyyy-mm-d;#")
'Sort Table
Call SortReceive
Call ProtectAll
Application.ScreenUpdating = True
'Return to Import File
curWorkbook.Activate
Exit Sub
'Check if previously created file is open and close it so new one can be saved
ErrFileClose:
FinalFileName = FileName & "_" & Format(Date, "[$-409]yyyy-mm-d;#") & ".xlsx"
Workbooks(FinalFileName).Close SaveChanges:=True
ActiveWorkbook.SaveAs FileName:=HLink _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Resume Next
End Sub

Saving .txt as .csv cancels all changes made by macro in the file. How to prevent it?

The issue continues this topic and is associated with my earlier post.
The code should deal with .csv files changing cells' values and interior color. It does its job, but after saving .txt as .csv I end up with something that looks like the source file - no changes visible.
I thought of using dictionaries, but to my understanding, to do so, I had to edit the newly saved .csv, which is exactly what I am trying to avoid in the below code. Does anyone have an idea how to have the changes saved?
Option Explicit
Sub fixCellsValue()
Dim wrk As Workbook
Dim Sh As Worksheet
Dim SourceFolder As String, Path As String, TmpFlName As String
Dim i As Long, lastrow As Long
SourceFolder = ThisWorkbook.Path & "\source"
'creating temporary .txt file
If Dir(SourceFolder & "SomeFile.*") <> "" Then
If InStr(1, Dir(SourceFolder & "SomeFile.*"), ".csv") Then
TmpFlName = SourceFolder & "\TmpCsv.txt"
If Dir(TmpFlName) <> "" Then Kill TmpFlName
FileCopy SourceFolder & "SomeFile.csv", TmpFlName
Workbooks.OpenText Filename:=TmpFlName, origin:= _
1250, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, Comma:=False _
, Space:=False, Other:=False, TrailingMinusNumbers:=True, Local:=False
Set wrk = Application.Workbooks("TmpCsv.txt")
Set Sh = wrk.Worksheets(1)
lastrow = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).row
'implementing changes to the temporary .txt file
For i = 2 To lastrow
If Len(Sh.Cells(i, 5)) > 10 Then
Sh.Cells(i, 5) = Left$(Sh.Cells(i, 5).Value, 10)
Sh.Cells(i, 5).Interior.ColorIndex = 6
End If
Next i
End If
End If
'saving as .csv file and deleting .txt file
If InStr(1, wrk.Name, "TmpCsv.txt") Then
wrk.SaveAs Filename:=Dir(SourceFolder & "SomeFile.*"), FileFormat:=xlCSV, Local:=True
wrk.Close Savechanges:=True
Kill TmpFlName
End If
End Sub
What looked as a simple opening semicolon delimited text /cvs file in your earlier post is now looks complicated. Even overlooking other issues, in my trial, I find while saving txt/csv files from excel it may introduce some double quote in the saved file (depending on position of comma, spaces and semicolon in a line). May refer links (Saving a Excel File into .txt format without quotes) and link and link2
As what I understand, your requirement is simple to truncate 5th column of the semicolon delimited file with csv extension and save it back, the simple approach of may solve your the problem. However, I still not satisfied with the workaround approach and invite more simple and straight approach to solve the problem (consisting txt file with comma, spaces and semicolons, while semicolon is to be treated as delimiter)
Try
Sub test2()
Dim Fname As String, Path As String, Txt As String, Txt2 As String
Dim INum As Integer, ONum As Integer, TrucTo As Integer, ColNo As Long
Dim Cols As Variant
' Modify the variables to your requirement
Path = "C:\Users\user\Desktop\"
Fname = "Somefile.csv" ' Target file name
Fname2 = "Somefile2.csv" ' Temp file name
TrucTo = 10 ' truncated to chars
ColNo = 4 ' column to be truncated -1
If Dir(Path & Fname2) <> "" Then Kill Path & Fname2
INum = FreeFile
Open Path & Fname For Input As #INum
ONum = FreeFile
Open Path & Fname2 For Output As #ONum
Do Until EOF(1)
Line Input #1, Txt
Cols = Split(Txt, ";")
If UBound(Cols) >= ColNo Then
If Len(Cols(ColNo)) >= truncto Then
Cols(ColNo) = Left(Cols(ColNo), TrucTo)
End If
End If
Txt2 = Join(Cols, ";")
Print #ONum, Txt2
Loop
Close #ONum
Close #INum
Kill Path & Fname
Name Path & Fname2 As Path & Fname
End Sub
This is the result input & Output

Renaming Excel to CSV Using VBA

I am trying to write a Macro in VBA using Excel 2010 that is linked to a button in a worksheet (located in Cell A1). When the button is pressed, a CSV should be generated that deletes columns A and B, so that column C effectively becomes column A. I am trying to also name the newly generated CSV based on the cell contents from cell A30 within the worksheet, but when I run the macro I am getting an error on the SaveAs function. I believe this is because cell A30 is deleted later on in the script. My question is where there is a way to use the Range (A30) to name the new CSV while still deleting that cell later on within the new CSV all within the same sub? I'm still new to VBA, so it is unclear to me why this is an issue when I would think that each command is executed sequentially, so once the CSV is saved with the new name, I would think I'd be able to delete the source of the file name.
Sub rpSaveCSV()
Dim ws As Worksheet
Set ws = ActiveSheet
'Saves current sheet of tracker as a CSV
ws.SaveAs "Y:\Drive\Youth " & Range("A30") & " .csv", FileFormat:=xlCSV
'Copies entire sheet and pastes values to get rid of formulas
ws.Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Select
Application.CutCopyMode = False
'Deletes first two columns and all remaining columns without content
Range("A:B").EntireColumn.Delete
Range("BI:XFD").EntireColumn.Delete
'Saves panel CSV
ActiveWorkbook.Save
'Opens Tracker up again
Workbooks.Open Filename:="Y:\Drive\Tracker.xlsm"
End Sub
Declare a variable to hold the string value:
Dim filename as String
filename = Range("A30")
'verify that "Y:\Drive\Youth " & filename & " .csv" is a valid file name:
Debug.Print "Y:\Drive\Youth " & filename & " .csv" ' looks right? Ctrl+G to find out
ws.SaveAs "Y:\Drive\Youth " & filename & " .csv", FileFormat:=xlCSV
'...delete columns...
'...do stuff...
Debug.Print filename 'value is still here!
I would recommend learning to use arrays with Excel data. It can often be far simpler than trying to replication Excel Application functions in VBA. And it is far more efficient/fast.
Here is a function that feeds the data to an array, and then prints the array to a csv (text) file.
Sub CreateCsvFromWorkSheet(leftColumn, rightColumn, FileName)
Set ws = ActiveSheet
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile(FileName, True)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
ar = ws.Range(ws.Cells(1, leftColumn), ws.Cells(lastRow, rightColumn))
For i = 1 To UBound(ar, 1)
strLine = ""
For j = 1 To UBound(ar, 2)
strLine = strLine & ar(i, j) & ","
Next
strLine = Left(strLine, Len(strLine) - 1)
f.WriteLine strLine
Next
f.Close
End Sub
You can call the function like this:
Sub TestRun()
FileName = "Y:\Drive\Youth " & Range("A30") & " .csv"
CreateCsvFromWorkSheet 3, 60, FileName
MsgBox "Complete."
End Sub

vba, how to import values from several excel files (selected by users via dialog box) into a master excel file?

I am quite new with VBA and trying to create a VBA which copy/paste specific ranges from multiple files (.xlsm) selected by a user into a master excel file. Basically I want to summarize the results for different scenarios into one excel file.
Until now, I have searched abit and managed to write a code which asks the files to be important. My problem is: I cant activate those files and start copy/pasting specific values into the master file.
I really appreciate if you can help me solve this. If you have a different idea, then it is also welcome. Many thanks..
Sub GetImportValues()
Dim finfo As String
Dim filterindex As String
Dim title As String
Dim filenames As Variant
Dim I As Integer
'Set up list of file filters
finfo = "Excel VBA files (*.xlsm), *.xlsm,"
filterindex = 1
'Set the dialog box caption
title = "pls select the excel files to Import"
'Get the filename
filenames = Application.GetOpenFilename(MultiSelect:=True)
If IsArray(filenames) Then
'Display full path and name of the files
Msg = "You selected:" & vbNewLine
For I = LBound(filenames) To UBound(filenames)
Msg = Msg & filenames(I) & vbNewLine
Next I
MsgBox Msg
Else
MsgBox "No excel file was selected."
End If
' start copy/pasting files one by one
For I = 1 To 10
Workbooks.Open filenames
Sheets("Report Tables").Range("D3").Select
Copy.Range (Selection.Offset(0, 11))
ThisWorkbook.Sheets("Results").Activate
Range("A3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Next I
End Sub
Try this code:
Sub GetImportValues()
Dim filenames, f
Dim myMsg As String
Dim wb As Workbook
Dim lastrow As Long
'Get the filename
filenames = Application.GetOpenFilename(FileFilter:="Excel VBA files (*.xls*), *.xls*", _
filterindex:=1, _
title:="pls select the excel files to Import", _
MultiSelect:=True)
If IsArray(filenames) Then
myMsg = "You selected:" & vbNewLine
'Display full path and name of the files
For Each f In filenames
myMsg = myMsg & f & vbNewLine
Next f
MsgBox myMsg
Else
MsgBox "No excel file was selected."
Exit Sub
End If
For Each f In filenames
Set wb = Workbooks.Open(f)
With ThisWorkbook.Sheets("Results")
'determine last non empty row in column A sheet "Result" to past result
lastrow = Application.Max(3, .Cells(.Rows.Count, "A").End(xlUp).Row + 1)
.Range("A" & lastrow).Value = wb.Sheets("Report Tables").Range("O3").Value
End With
wb.Close SaveChanges:=False
Set wb = Nothing
Next f
End Sub
Code above copies cell O3 from each workbook and paste it in Result sheet of ThisWorkbook in A3 for first file (actually it finds last non empty row), in A4 for second file and so on

Resources