Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are double quotes added at start/end of files?

Tags:

xml

excel

vba

Context: I have an Excel worksheet with 120 rows or so that I need to create files with.

Data is structured as follows:
The A column contains destination file names
The B column has the corresponding data to be written in each file

Giving us the following general layout
data file layout

To get data from B column written in each A column named files, I wrote the following:

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 is intended except, it encloses the file content between double quotes.

File content enclosed in double quotes:
enter image description here

So, in a case where a file named F1.xml should just contain <foo><bar>Baz</bar></foo>

My script transforms 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.

Should I declare messageitSelf as a different type?

like image 610
Laurent Morissette Avatar asked Nov 23 '25 11:11

Laurent Morissette


1 Answers

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
like image 102
Mathieu Guindon Avatar answered Nov 26 '25 15:11

Mathieu Guindon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!