skohaha
skohaha

Reputation: 11

printing txt file from VBA for Matlab

I am working parallel with Excel and VBA in order to create txt files I wish to use for MATLAB. However, I experience some format issues I can't resolve.

For instance, the following VBA

Open "example.txt" For Output As #1
    For i = 1 To 5
     Print #1, Sheets("Example").Cells(i + 3, 3)
    Next i

Indeed prints numbers (reals) it is supposed to however MATLAB struggles with reading this example .txt file.

There are some characters VBA is printing. I don't know how to delete those within a VBA code.

Example.txt opened in matlab. Note the NaN read by MATLAB from a text file:

Example.txt opened in matlab. Note NaN read by Matlab from a text file

VBA text file - Note a line as the first element of a column

VBA text file - Note a line as the first element of a column

Upvotes: 1

Views: 67

Answers (1)

Andreas
Andreas

Reputation: 23968

Perhaps there is a character that is invisible.
A possible solution is to remove those characters with regex.

Add reference to Microsoft VBScript Regular Expression 5.5

Then the following VBA code:

Set re = New RegExp
re.Pattern = "[^0-9]"

Open "example.txt" For Output As #1
For i = 1 To 5
    Print #1, re.Replace(Sheets("Example").Cells(i + 3, 3).value, vbNullString)
Next i

This should remove anything that is not a digit from the cell before printing it to the text document.

Upvotes: 0

Related Questions