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.
Related
Hello Dear StackOverFlowers,
My question may be trival but I'm currently out of option to think of after searching all afternoon
Context: I have a excel worksheet with 120 rows or so that I need to use to create files with.
Data is structured as follow:
The A column contains destination file names
B column has the corresponding data that needsto be written in each file
Giving us the following general layout
data file layout
So, to get data from B column written in each A column named files, I wrote the followin VBScript snippet:
Option Explicit
Sub writeExportedMsgToXML()
' wrote that tiny script not to have to copy pate 117 messages by hand to have ops put them back on Q
Dim currentRow As Integer
' modify to match your data row start and end
For currentRow = 2 To 11
Dim messageID As String
Dim messageitSelf As String
messageID = Trim(ActiveSheet.Range("A" & currentRow))
messageitSelf = ActiveSheet.Range("B" & currentRow)
Dim subDirectory As String
subDirectory = "xmls"
Dim filePath As String
filePath = ActiveWorkbook.Path & "\" & subDirectory & "\" & messageID & ".xml"
MsgBox (messageitSelf) ' for test purpose
Open filePath For Output As #1
Write #1, messageitSelf
Close #1
Next currentRow
End Sub
The script does mostly what it's intended for Except , and this is the source of my question today, it enclose the file content between double quotes as you can see below:
file content enclosed in double quotes
So, in a case where a file named F1.xml should just contain <foo><bar>Baz</bar></foo>
My script transform it as "<foo><bar>Baz</bar></foo>"
What I tried
Replacing file writing part with the following
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
objStream.Charset = "UTF-8"
Dim subDirectory As String
subDirectory = "xmls"
Dim filePath As String
filePath = ActiveWorkbook.Path & "\" & subDirectory & "\" & messageID & ".xml"
objStream.Open
objStream.WriteText messageitSelf
objStream.SaveToFile filePath
objStream.Close
With same outcome
Any clues on what I'm missing/Doing wrong ?
Should I declare messageitSelf as a different type ?
Any help would be appreciated :)
Thank you
Write# statements surround strings with double quotes:
Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file.
Use Print# instead:
Dim fn As Long
fn = VBA.FreeFile
Open filePath For Output As #fn
Print #fn, messageitSelf
Close #fn
How do I change the file path when writing a VBA (Excel) application that writes from an Excel file into a text file? Whatever I do, it either just gives me an error or creates it in the same folder (Documents).
Full relevant code:
Dim x As Integer
Dim tmp As String
Sub CommandButton1_Click()
Dim File As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
File = Application.DefaultFilePath & "\Viteria_mancante_o_in_esaurimento.txt"
Set rng = Selection
Open myFile For Append As #1
cellValue = Range("C2").Value
Write #1, cellValue
cellValue = Range("D2").Value
Write #1, cellValue
Close #1
tmp = "C" + CStr(12 + x) + ":" + "D" + CStr(12 + x)
Worksheets("Foglio2").Range(tmp).Value2 = Worksheets("Foglio2").Range("C2:D2").Value2
x = x + 1
End Sub
EDIT:
Added image of cells turning red.
Replace this line:
File = Application.DefaultFilePath & "\Filename.txt"
With the full path where you want the file location. For example:
File = "C:\MyFolder\Filename.txt"
And correct this line:
Open myFile For Append As #1
To this:
Open File For Append As #1
I also suggest that you add option explicit at the beginning of the vba module so you prevent from having undeclared variables
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
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
I need to select a text file to import into Excel where the name of the text file contains a string of text that matches a cell in the Excel spreadsheet.
Eg.
A cell with a value "D12345"
I need to import a text file into the sheet where the same string (i.e. "D12345") is contained in the name of the text file.
The selection needs to be made from a collection of text files. Only 1 file in the collection will contain the matching string.
Hope that makes sense.
Give this a try:
Sub SimpleFileListre()
Dim s As String, FileName As String
Dim mesage As String
Range("A:A").Clear
s = "C:\TestFolder\*.txt"
sFolder = "C:\TestFolder\"
FileName = Dir(s)
Do Until FileName = ""
If InStr(1, FileName, "D12345") > 0 Then
Call GetStuff(sFolder & FileName)
End If
FileName = Dir()
Loop
End Sub
Sub GetStuff(s)
Close #2
Open s For Input As #2
j = 1
Do While Not EOF(2)
Line Input #2, TextLine
Cells(j, 1) = TextLine
j = j + 1
Loop
Close #2
End Sub