Export excel rows to individual text files - excel

I'm using the VBA code below to export Excel rows to individual text file (file name is Column B)
Sub ExportTextFiles()
Dim i As Long
Dim LastDataRow As Long
Dim MyFile As String
Dim fnum
LastDataRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To LastDataRow
'The next line uses the contents of column B on the same row to name it
MyFile = "C:\test\" & ActiveSheet.Range("B" & i).Value & ".txt"
fnum = FreeFile()
Open MyFile For Output As fnum
Print #fnum, Format(Range("A" & i))
Close fnum
Next i
End Sub
My problem is only 255 Characters of row exported in the text.
is there a workaround ?

For reasons that I have not been able to find clear documentation, when you use the Format function with no format defined, it will return only 255 characters.
I don't understand why you need to use the Format function in your Print statement, but if you remove it, the 255 character limitation seems to disappear.
The only thing I think you might have to worry about is the cell contents limitation of 32,767 characters.

Related

How to copy paste tables from many txt files into 1 excelsheet?

Steps I need to do:
Open all necessary files(which are from the same folder) in Excel
For the first file, copy from row 6 to bottom of table. For second and subsequent files, copy from row 7 to bottom of table (Note that each file has different number of table rows). (Reasoning is that rows 1-5 are irrelevant, row 6 has heading, and I only want the heading to appear once in the table)
Paste into main excelsheet, but without overlapping previous rows
Separate main excelsheet by commas (text to column)
Close all files other than main excelsheet
Tried to google the various steps, but each step's code does not work well with one another, resulting in numerous errors, so I gave up and tried to record macro, but I did not get a "for" loop.
I've just tested the code below
Sub Read_Texts()
'Variable Declaration
Dim sFilePath As String
Dim sFileName As String
'Specify File Path
sFilePath = "C:\Users\use\Desktop\New folder"
'Check for back slash
If Right(sFilePath, 1) <> "\" Then
sFilePath = sFilePath & "\"
End If
sFileName = Dir(sFilePath & "*.txt")
Do While Len(sFileName) > 0
If Right(sFileName, 3) = "txt" Then
'Display file name in immediate window
Dim hf As Integer: hf = FreeFile
Dim lines() As String, i As Long
Open sFileName For Input As #hf
lines = Split(Input$(LOF(hf), #hf), vbNewLine)
Close #hf
If sFileName = "file1.txt" Then
For i = 5 To UBound(lines)
Debug.Print "File 1 Line"; i; "="; lines(i)
Next
Else
For i = 6 To UBound(lines)
Debug.Print "File 1 Line"; i; "="; lines(i)
Next
End If
End If
'Set the fileName to the next available file
sFileName = Dir
Loop
End Sub
Change C:\Users\use\Desktop\New folder according to your folder path, and here you can do whatever with the returned lines Debug.Print "File 1 Line"; i; "="; lines(i)

Excel vba for exporting cell content to TXT file

I have an Excel file (https://www.dropbox.com/s/hv9u68s136es190/Example2.xlsx?dl=0) with in column A all the persons and in the cell next to there name text (column B).
I want to save for every person a text file containing the text in the cell next to there name.
The filename should be called like the persons name.
So in this case i would have three text files. I do not know how to manage this using VBA in Excel.
Can someone help me with this?
Try this code, please. But, you must initially try something on your own. We usually help people correct their code and learn...
The text files will be named like the people names in column A. The folder where they will be saved will be the one of the workbook which keeps the active sheet. You can define it as you need, of course.
Option Explicit
Sub SaveTxtNamePlusTekst()
Dim sh As Worksheet, lastR As Long, i As Long, strPath As String
Set sh = ActiveSheet ' use here the sheet you need
strPath = sh.Parent.path 'you can define here the path you wish...
If Dir(strpath, vbDirectory) = "" Then MsgBox "The folder path is not valid...": Exit Sub
lastR = sh.Range("A" & Cells.Rows.Count).End(xlUp).row 'Last row in A:A
For i = 2 To lastR
'calling a Sub able to create a text file in a folder and put text in it
WriteText sh.Range("A" & i).value, strPath, sh.Range("B" & i).value
Next i
End Sub
Private Sub WriteText(strName As String, strPath As String, strText As String)
Dim filePath As String
filePath = strPath & "\" & strName & ".txt" 'building the txt file path
FreeFile 1
Open filePath For Output As #1
Print #1, strText 'write the text
Close #1
End Sub

Excel to Text VBA precedes with question mark - how to fix?

I'm very new to VBA in Excel. I'm using this code I cobbled together from example snippets online to convert a column of cells in Excel to a text file:
Private Sub CommandButton1_Click()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
Dim FName As String
Dim FPath As String
Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object
fsT.Type = 2: 'Specify stream type – we want To save text/string data.
fsT.Charset = "utf-8": 'Specify charset For the source text data.
FPath = "C:\WHIT\ParamGen"
FName = Sheets("Sheet1").Range("b49").Text
myFile = FPath & "\" & FName
Set rng = Range("B2: B42 ")
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
Print #1, cellValue
Else
Print #1, cellValue,
End If
Next j
Next i
Close #1
End Sub
The problem is that the first cell in my Excel file contains this text:
#!=1
...and it shows up in the generated text file like this:
?#!=1
Everything else in the excel file gets written to the text file without issue, but that question mark messes up the import function in the software this file is being generated for.
Any ideas on getting this question mark to disappear?
Have you tried removing the "?" with code in the file, such as:
If left(cellvalue,1)="?" then
application.substitute(cellvalue,"?","")
end if
I ran this code with the first cell containing #!=1 and it wrote correctly to the text file as #!=1 (no ? added). Did you check to see if cell B2 contains any non-printable characters?
I found a solution. Excel was treating the #!=1 in the first cell as a function, but it wasn't a functional function. My best guess is that it was throwing an invisible character in there as it parsed it into a text file. Overwriting the offending cell with '#!=1 did the trick.

Trying to export a range in Excel to CSV with only cells that contain data

Good afternoon all,
I am building an excel sheet for my coworkers to use to generate CSV files. I need to get an output with header row and then all the data from the sheet. It will be no more than 40 rows, but could be less rows. I currently have a lot of formulas in the sheet doing the heavy lifting for my coworkers on things like generating usernames/etc from the input data. I need to have them click a button and get the CSV file on the other end. My current issues are as follows.
1.) my CSV contains double quotes on every field, even though commas should not be in the input data. I need to prevent this as the program we are feeding these csv files to does not like the double quotes AT ALL. Yes, I know you can open it in notepad and replace all to remove them but im trying to build a one click solution as some of the folks using this are not very tech savvy.
2.) my macro is exporting all forty rows of data currently. I need it to only export the rows that contain data. Theoretically with the formulas built there should be no "partial" rows, only a full row or a blank row.
3.) When generating the CSV file its not appending a filetype at all, I need it to specify a .txt. filetype if at all possible as again, the program we are feeding these to is very picky.
Sub CommandButton1_Click()
Dim filename As String
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
filename = InputBox("Please enter file name", "Save as CSV", "CSV_" & Format(Now, "DD_MM_yyyy"))
myFile = Application.DefaultFilePath & filename
Set rng = Range("A1:J41")
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
This is what your code would have to look like. Unfortunately I wasn't able to get rid of the double quotes, maybe someone else has an idea for that.
Sub csvExport()
Dim filename As String
Dim myFile As String, cellValue As Variant, i As Integer, j As Integer
Dim ws As Worksheet
filename = "\" & InputBox("Please enter file name", "Save as CSV", "CSV_" & Format(Now, "DD_MM_yyyy")) & ".txt"
myFile = Application.DefaultFilePath & filename
Set ws = Worksheets("YOURSHEETNAME")
With ws
Open myFile For Output As #1
For i = 1 To .UsedRange.Rows.Count
For j = 1 To .UsedRange.Columns.Count
cellValue = .Cells(i, j).Value
If j = .UsedRange.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End With
End Sub

Titles in one CSV, Hyperlinks in other CSV, create new CSV with links built in

I have plain text titles in one .csv and hyperlinks for those titles in another .csv
I currently open them in the same work book, put the titles in A, the hyperlinks in H, and use
=HYPERLINK(H1,A1)
to get my final output of Titles with hyperlinks built in.
Is there an easy way (Excel VBA or macro) to bypass the manual work and create a new output file with the "Titles with hyperlinks built in" from the original two .csv files?
Edit: My two .csv files have the respective text (hyperlink and titles) all down column A.
Sub buildlinks()
Dim i As Integer
Dim wb1, wb2 As Workbook
Set wb1 = Application.Workbooks.Open("C:/path/Links.csv")
Set wb2 = Application.Workbooks.Open("C:/path/Titles.csv")
i = 1
Do Until wb1.Sheets("Sheet1Name").Cells(i, 1).Value = ""
ThisWorkbook.Sheets("Sheet1Name").Cells(i, 1).Formula = "=HYPERLINK(" & wb1.Sheets("Sheet1Name").Cells(i, 1).Value & "," & wb2.Sheets("Sheet1Name").Cells(i, 1).Value & ")"
i = i + 1
Loop
End Sub
Assuming you want to create the hyperlinks in the current spreadsheet instead of creating a separate file.
Since you've said that the inputs are really just text files, one item per line, not comma-separated, it's actually pretty simple to implement using the VBA file handling commands.
Sub BuildLinks(titlesFilePath as String, linksFilePath As String, ByVal rowStart As Long)
Dim tf As Long, lf As Long, of As Long
tf = FreeFile
On Error Goto NO_TITLE_FILE
Open titlesFilePath For Input As #tf
lf = FreeFile
On Error Goto NO_LINKS_FILE
Open linksFilePath For Input As #lf
On Error Goto 0
While Not (EOF(tf) Or EOF(lf))
Dim curTitle As String, curLink As String
Line Input #tf, curTitle
Line Input #lf, curLink
Cells(rowStart, 1).Formula = "=HYPERLINK(""" & curLink & """,""" & curTitle & """)"
Wend
Close #tf
Close #lf
Exit Sub
NO_TITLE_FILE:
MsgBox "Can't Open Title File" & titlesFilePath
Exit Sub
NO_LINKS_FILE:
MsgBox "Can't Open Links File" & linksFilePath
End Sub

Resources