I would like opinions/suggestions for improvement etc on the following function. It will be wrapped around every value being passed into a CSV file on a classic ASP page. As is below it is handling all situations we are up against, for now....
I would like to know why If Len(txt) = 0 Then fails when it is run in the page that creates the CSV file althouh runs fine when in a regular ASP page. I ma having to use If "" & txt = "" Then to make it work on both pages
function insertCSV(txt)
'If Len(txt) = 0 Then
If "" & txt = "" Then
Exit Function
Else
Dim tmp
tmp = txt
if isNumeric(tmp) then
if left(tmp, 1) = "0" then
tmp = """" & tmp & """"
else
tmp = tmp
end if
else
tmp = Replace(tmp, """", """""")
if instr(tmp, ",") or instr(tmp, """") then tmp = """" & tmp & """"
if instr(tmp, "®") then tmp = replace(tmp, "®", "®")
if instr(tmp, "™") then tmp = replace(tmp, "™", "™")
if instr(tmp, "©") then tmp = replace(tmp, "©", "©")
if instr(tmp, vbcrlf) then tmp = replace(tmp, vbcrlf, "")
if instr(tmp, "Â") then tmp = replace(tmp, "Â", "")
end if
insertCSV = tmp
End If
end function
Few things:
This section:
If you just want to return an empty string if
txt
is empty, you can just do this:You don't need to use
End If
for single-lineIf
statements.This line:
You're assigning the value back to itself? What purpose does this serve?
Don't you want to replace just the symbol
©
with©
? The way you have it written, you're replacing the entire text with©
(same goes for your other tests). I would think you'd want to do this instead:Try making those changes and then post an updated version of your routine and let's see how it looks.
You don't need any of that the issue is Excel interprets the CSV as
ASCII
when you are sending it asUTF-8
. There is a useful trick that fools Excel into using the correct encoding rather then assuming ASCII, I use this technique all the time and works well. It involves writing a BOM (Byte Order Mark) to the stream before displaying your data that tells Excel the data isUTF-8
notASCII
encoded.This should be specified before you use
Response.Write()
to output your text from theinsertCSV()
function.Using this kind of code
is just wrong when what the output (
Â
) is trying to do is tell you something is wrong with the encoding.Useful Links