Open and write in txt file from Excel macro - excel

I need help with code, I want my macro to open a .txt file and write only 1-9 rows(copy from Excel) in one txt file and then open next .txt file and write 9-18 and so on until data in the excel rows is finished under each column.
Below code only paste 1-9 rows from Excel to Txt file and stop.
So it means if I have 36 rows in Excel(A1-A36) it should create 3 txt files each with 9 rows only.
Sub env_gen()
Dim filename As String
Dim linetext As String
Dim my_range As Range
filename = ThisWorkbook.Path & "\Monday123" & ".txt"
Open filename For Output As #1
Set my_range = Worksheets("sheet1").Range("A1:A9")
For i = 1 To 9
For j = 1 To 1
linetext = IIf(j = 1, "", linetext & ",")
Next j
Print #1, linetext
Next i
Close #1
MsgBox ("File is created")
End Sub

To iterate over a range, you can use a loop and put the index inside the range address. Eg. For i = 1 to 9: Cells(i, 1) = .... This loop can also use the ranges size as a parameter to ensure you loop over the whole range and only the range (no extra). Eg. For i = 1 To my_range.Rows.Count.
When looping within a loop, you can also use the outer loops index as a parameter for the inner loop. Eg. For i = 1 to 36 Step 9: For j = i to i + 8
Here is an example of those techniques implemented with your code:
Sub env_gen()
Dim filename As String
Dim linetext As String
Dim CurrentStep As Long
Dim my_range As Range
Set my_range = Worksheets("sheet1").Range("A1:A36")
For i = 1 To my_range.Rows.Count Step 9
CurrentStep = CurrentStep + 1
filename = ThisWorkbook.Path & "\Monday123 (" & CurrentStep & ").txt"
Open filename For Output As #1
For j = i To i + 8
linetext = my_range.Cells(i).Text & IIf(j <> i + 8, "", ",")
Print #1, linetext
Next j
Close #1
Next i
MsgBox ("Files are created")
End Sub

Related

How to write a TXT from multiple sheets, same range, into one file?

I am a real novice at VBA, so any help would be welcome. I am trying to convert certain ranges across multiple sheets into only one file. I have written code for a similar situation that produces a TXT file for each sheet, however now I need the same sheets/same ranges into only one TXT file. My original setup would produce about 30 files from 30 sheets, so now I would need all 30 sheets in a specific range in one file. Here is my original code:
Dim linetext As String
Dim myrange As Range
Dim FileName As String
' Next Sheet tab for conversion
FileName = ThisWorkbook.Path & "\" & "50002 LIGHTING" & ".txt"
Open FileName For Output As #1
Set myrange = Sheet1.Range("J11:L161")
For i = 1 To 150
For j = 1 To 3
linetext = IIf(j = 1, "", linetext & vbTab) & myrange.Cells(i, j)
Next j
Print #1, linetext
Next i
Close #1
FileName = ThisWorkbook.Path & "\" & Sheet5.Range("D7") & " " & Sheet5.Range("C6") & ".txt"
Open FileName For Output As #5
Set myrange = Sheet5.Range("J11:L161")
For i = 1 To 150
For j = 1 To 3
linetext = IIf(j = 1, "", linetext & vbTab) & myrange.Cells(i, j)
Next j
Print #5, linetext
Next i
Close #5
' Next Sheet tab for conversion
MsgBox (All Files Transformed from Excel to .TXT")
End Sub
Export Ranges
Option Explicit
Sub ExportRanges()
Const ExportFileName As String = "Test.txt"
Const ExportRangeAddress As String = "J11:L161"
Dim WorksheetObjects As Variant
WorksheetObjects = VBA.Array(Sheet1, Sheet5)
Dim FilePath As String: FilePath = ThisWorkbook.Path & "\" & ExportFileName
Dim FileNum As Long: FileNum = FreeFile
Open FilePath For Output As FileNum
Dim Data As Variant
Dim n As Long, rCount As Long, cCount As Long, r As Long, c As Long
Dim LineText As String
For n = 0 To UBound(WorksheetObjects)
Data = WorksheetObjects(n).Range(ExportRangeAddress).Value
If n = 0 Then
rCount = UBound(Data, 1)
cCount = UBound(Data, 2)
End If
For r = 1 To rCount
For c = 1 To cCount
LineText = IIf(c = 1, "", LineText & vbTab) & Data(r, c)
Next c
Print #FileNum, LineText
Next r
Next n
Close FileNum
MsgBox "Ranges exported to text file.", vbInformation
End Sub

Exporting sets of rows from Excel to txt files

My objective is to take 99 rows in groups of 10 containing 9 rows each and 2 columns to make dat(text) files.
This can be achieved using loops by breaking the writing operation at 9th row and then resuming at 10th row.
I want the first 10 rows from Excel in one dat file, next 10 in another and so on.
When I run the following code, nothing happens. When I debug, it skips the loop structure. When I run it for just one file containing all the rows it runs perfectly.
0.8641 0.8654
0.6605 0.8269
0.5828 0.8269
0.9985 1.0000
0.7527 0.9423
0.6641 0.9423
1.1329 1.1346
0.8756 1.0962
0.7590 1.0769
0.9174 0.8836
0.7557 0.8443
0.5986 0.8164
0.9984 1.0000
0.8085 0.9656
0.6809 0.9443
1.0972 1.1328
0.8680 1.0902
0.7453 1.0623
0.8665 0.8714
0.6385 0.8429
0.5398 0.8143
Private Sub CommandButton1_Click()
' Variable declaration
Dim FilePath As String
Dim CellData As String
Dim Folder As String
Dim del As String
Dim LastCol As Long
Dim LastRow As Long
Dim FileNum As Integer
Dim count As Integer
Dim counter As Integer
Dim i, j, k As Integer
' Getting the last row and column from the workbook
LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
Foler = "C:\TRNSYS1832-bit\TRNSYS18\MyProjects\Main project\Chiller and ice storage data\Excel\"
del = vbTab
count = 9
conuter = 1
For k = 1 To k = LastRow
FilePath = Folder & "Data" & counter & ".txt" ' This is the final name example - Data1.txt
FileNum = FreeFile ' FreeFile so that I don't have to associate it with a specific number
Open FilePath For Output As #FileNum ' Opening the file for writing
Print #FileNum, "-5" & vbTab & "0" & vbTab & "5" & " !Chilled water leaving temperature (C)"
Print #FileNum, "35" & vbTab & "45" & vbTab & "50" & " !Cooling water entering temperature (C)"
For i = 1 To count
For j = 1 To LastCol
If j = LastCol Then
CellData = CellData & Round(Cells(i, j).Value, 4)
Else
CellData = CellData & Round(Cells(i, j).Value, 4) & del
End If
Next j
Print #FileNum, CellData
CellData = ""
Next i
Close #FileNum
i = count + 1
count = count + 9
counter = counter + 1
Next k
End Sub
Could it be as simple as the misspelling in the folder in the following line of code?
Foler = "C:\TRNSYS1832-bit\TRNSYS18\MyProjects\Main project\Chiller and ice storage data\Excel\"
Looking at the rest of the code, Folder is not set to anything.
This line also has a spelling mistake:
conuter = 1
The first time through, counter = 0, it gets set to 1 the first time through the loop.
Another error I think:
For k = 1 To k = LastRow
Should be
For k = 1 To LastRow

How can I improve my export from Excel selection to text file?

I'm trying to export Excel data to individual text files. Currently, the code I've got below exports the selection in Excel to a file titled "AgreementText.txt". I'd like to do two things to improve it, but I'm not sure how:
Firstly, I want to title each .txt file something different. The titles of the files are listed in a column 4 spaces to the left of each selection. Is there any way I can grab the title each time from that column?
Secondly, the text currently appears in the text file with quotation marks around it. Is there any way I can remove those?
Edit: Thirdly, I also need to specify a different file path to the default, but I'm not sure how.
Thanks in advance!
Sub TextFileExport()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
myFile = Application.DefaultFilePath & "\AgreementText.txt"
Set rng = Selection
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End Sub
Firstly, the title can easily just get retrieved by getting the cell value. Assuming it will be in the same row as the top of your selection, but 4 columns to the right, you can do it as follows:
myFile = Application.DefaultFilePath & "\" & Selection.Cells(1, Selection.Columns.Count + 4) & ".txt"
Open myFile For Output As #1
Secondly, you can use Print instead of Write to print without quotes. I find the easiest is to just build the whole line you want to write as one string and then do a single Print command for each line.
Putting it all together:
Sub TextFileExport()
Dim myFile As String
Dim rng As Range
Dim line
Dim i As Integer
Dim j As Integer
Set rng = Selection
myFile = Application.DefaultFilePath & "\" & rng.Cells(1, rng.Columns.Count + 4) & ".txt"
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
line = ""
For j = 1 To rng.Columns.Count
line = line & rng.Cells(i, j).Value
If j < rng.Columns.Count Then
line = line & ","
End If
Next
Print #1, line
Next
Close #1
End Sub

#copy from excel and paste to notepad using VBA

I am able to print the values from excel to notepad, but the format is bit different,
Dim txtFile As String, rng As Range, cellValue As Variant, r As Integer, c As Integer
txtFile = slocation & "\" & "Cont_name_" & Filename & ".txt"
lrow = Range("I" & Rows.Count).End(xlUp).Row
Range("A2:G" & lrow).Select
Set rng = Selection
Open txtFile For Output As #1
For r = 1 To rng.Rows.Count
For c = 1 To rng.Columns.Count
cellValue = rng.Cells(r, c).Value
If InStr(cellValue, "/") Then
cellValue = Format(cellValue, "yyyyMMDD")
End If
If c = rng.Columns.Count Then
Print #1, cellValue
Else
Print #1, cellValue,
End If
Next c
Next r
Close #1
Spaces are more than the requirement, please help to achieve the desired output,because the tool is accepting only the desired format
Your first output uses the standard "print zones" in every 14th column (positions 1, 15, 29, ...), which you get by printing with appended comma
.............|.............|.............|.............|.............|.............|
XXX-XX-XXXX 20190111 AA 123 NAME NAME XXXXX
Your desired output starts at the next multiple of 8 characters (1, 9, 17, ...)
.......|.......|.......|.......|.......|.......|.......|.......|.......|
XXX-XX-XXXX.....20190111........AA......123.....NAME....NAME....XXXXX
You can set the next print position in your file by Seek
Private Sub SaveAsText()
Dim rng As Range
Dim r As Long, c As Long
Set rng = ActiveSheet.Range("A1:G1")
Dim file1 As Integer
file1 = FreeFile
Open ThisWorkbook.Path & "\test.txt" For Output As file1
For r = 1 To rng.Rows.Count
For c = 1 To rng.Columns.Count
If c = 1 Then
Print #file1, CStr(rng.Cells(r, c).Value);
Else
Seek #file1, (Seek(file1) \ 8 + 1) * 8 + 1
Print #file1, CStr(rng.Cells(r, c).Value);
End If
Next c
Next r
Close #file1
End Sub
Additional Hints:
Use Freefile to get the next free file number (which might be 1).
Use CStr() to prevent the automatically added space characters before and after numeric values.

Excel VBA to write only rows with text to txt file

I have a table (Table8) that I need to export as .txt file.
The code I'm currently using works fine but also exports empty rows from the table which messes up the .txt file for further use.
The table will have information in 1 to n rows (usually not more than 100).
I would like to only export those rows, which have text in them (other rows have a formula in them and currently appear as blank in .txt file).
Code I'm currently using:
Sub saveToMtext()
Dim filename As String, lineText As String
Dim myrng As Range, i, j
filename = ThisWorkbook.path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
ChDir (ThisWorkbook.path)
Open "m_text.txt" For Output As #1
FileFormat = xlText & CreateBackup = False
Set myrng = Range("Table8")
For i = 1 To myrng.Rows.Count
For j = 1 To myrng.Columns.Count
lineText = IIf(j = 1, "", lineText & vbTab) & myrng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
End Sub
I changed from regular IF to IF x Then Exit For and got it working.
Final code:
Sub saveToMtext()
Dim filename As String, lineText As String
Dim myrng As Range, i, j
Dim LValue As String
filename = ThisWorkbook.path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
ChDir (ThisWorkbook.path)
Open "m_text.txt" For Output As #1
FileFormat = xlText & CreateBackup = False
Set myrng = Range("Table8")
k = 11
For i = 1 To myrng.Rows.Count
LValue = Cells(k, 121)
m = Len(LValue)
If m < 1 Then Exit For
For j = 1 To myrng.Columns.Count
lineText = IIf(j = 1, "", lineText & vbTab) & myrng.Cells(i, j)
Next j
Print #1, lineText
k = k + 1
Next i
Close #1
End Sub

Resources