How can I generate GUIDs in Excel? - vba

I have an excel file with one order on each row, and I want each order to have a unique identifier, so there will be a Unique ID column. Every time I fill a row, I want Excel to automatically populate the Unique ID column for me. I did some research and was pointed in the direction of GUIDs. I found the following code:
Function GenGuid() As String
Dim TypeLib As Object
Dim Guid As String
Set TypeLib = CreateObject("Scriptlet.TypeLib")
Guid = TypeLib.Guid
' format is {24DD18D4-C902-497F-A64B-28B2FA741661}
Guid = Replace(Guid, "{", "")
Guid = Replace(Guid, "}", "")
Guid = Replace(Guid, "-", "")
GenGuid = Guid
End Function
but I am not sure how I can implement it. Any help would be greatly appreciated. Thank you in advance.

The following Excel expression evaluates to a V4 GUID:
=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,65535),4),"-",DEC2HEX(RANDBETWEEN(16384,20479),4),"-",DEC2HEX(RANDBETWEEN(32768,49151),4),"-",DEC2HEX(RANDBETWEEN(0,65535),4),DEC2HEX(RANDBETWEEN(0,4294967295),8))
-or (depending on locale setting/decimal and list separators)-
=CONCATENATE(DEC2HEX(RANDBETWEEN(0;4294967295);8);"-";DEC2HEX(RANDBETWEEN(0;65535);4);"-";DEC2HEX(RANDBETWEEN(16384;20479);4);"-";DEC2HEX(RANDBETWEEN(32768;49151);4);"-";DEC2HEX(RANDBETWEEN(0;65535);4);DEC2HEX(RANDBETWEEN(0;4294967295);8))
Note that the first character of the third group is always 4 to signify a V4 (pseudo-random number generated) GUID/UUID per RFC 4122 section 4.4.
Also note that the first character of the fourth group is always between 8 and B per the same RFC.
Standard disclaimer: the resulting GUIDs/UUIDs are not cryptographically strong.
Edit: remove invisible characters

I used the following function in v.2013 excel vba to create a GUID and is working well..
Public Function GetGUID() As String
GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36)
End Function

I know this question is answered, but I think the code in question should look something like what's on this page: http://snipplr.com/view/37940/
Haven't tested, but this code seems to tap into the Windows API to get its GUID's - I would try putting that in a public module and typing =GetGUId() in an Excel cell to see what I'd get. If it works in VB6 you have a great deal of a good chance it works in VBA as well:
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "OLE32.DLL" (pGuid As GUID) As Long
Public Function GetGUID() As String
'(c) 2000 Gus Molina
Dim udtGUID As GUID
If (CoCreateGuid(udtGUID) = 0) Then
GetGUID = _
String(8 - Len(Hex$(udtGUID.Data1)), "0") & Hex$(udtGUID.Data1) & _
String(4 - Len(Hex$(udtGUID.Data2)), "0") & Hex$(udtGUID.Data2) & _
String(4 - Len(Hex$(udtGUID.Data3)), "0") & Hex$(udtGUID.Data3) & _
IIf((udtGUID.Data4(0) < &H10), "0", "") & Hex$(udtGUID.Data4(0)) & _
IIf((udtGUID.Data4(1) < &H10), "0", "") & Hex$(udtGUID.Data4(1)) & _
IIf((udtGUID.Data4(2) < &H10), "0", "") & Hex$(udtGUID.Data4(2)) & _
IIf((udtGUID.Data4(3) < &H10), "0", "") & Hex$(udtGUID.Data4(3)) & _
IIf((udtGUID.Data4(4) < &H10), "0", "") & Hex$(udtGUID.Data4(4)) & _
IIf((udtGUID.Data4(5) < &H10), "0", "") & Hex$(udtGUID.Data4(5)) & _
IIf((udtGUID.Data4(6) < &H10), "0", "") & Hex$(udtGUID.Data4(6)) & _
IIf((udtGUID.Data4(7) < &H10), "0", "") & Hex$(udtGUID.Data4(7))
End If
End Function
Thanks Gus Molina!
If this code works (which I don't doubt), I think you'd get a new set of GUID's whenever the function gets evaluated, which means everytime the sheet gets calculated - when you're saving the workbook, for example. Make sure to copy-pastespecial-values if you need the GUID's for later use... which is somewhat likely.

A VBA approach based on generating random numbers using the Rnd() function, and not on external API calls or Scriptlet.TypeLib:
Public Function CreateGUID() As String
Do While Len(CreateGUID) < 32
If Len(CreateGUID) = 16 Then
'17th character holds version information
CreateGUID = CreateGUID & Hex$(8 + CInt(Rnd * 3))
End If
CreateGUID = CreateGUID & Hex$(CInt(Rnd * 15))
Loop
CreateGUID = "{" & Mid(CreateGUID, 1, 8) & "-" & Mid(CreateGUID, 9, 4) & "-" & Mid(CreateGUID, 13, 4) & "-" & Mid(CreateGUID, 17, 4) & "-" & Mid(CreateGUID, 21, 12) & "}"
End Function
This essentially is a VBA implementation of NekojiruSou's answer (it also generates a v4 GUID), and carries the same limitations, but will work in VBA and might be easier to implement.
Note that you can omit the last line to not return the dashes and curly braces in the result.

I found pretty solution here:http://www.sql.ru/forum/actualutils.aspx?action=gotomsg&tid=751237&msg=8634441
Option Explicit
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(0 To 7) As Byte
End Type
Private Declare Function CoCreateGuid Lib "ole32" (pguid As GUID) As Long
Private Declare Function StringFromGUID2 Lib "ole32" ( _
rguid As GUID, ByVal lpsz As Long, ByVal cchMax As Long) As Long
Public Function CreateGUID() As String
Dim NewGUID As GUID
CoCreateGuid NewGUID
CreateGUID = Space$(38)
StringFromGUID2 NewGUID, StrPtr(CreateGUID), 39
End Function

This is based on a javascript implementation.
Private Function getGUID() As String
Call Randomize 'Ensure random GUID generated
getGUID = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
getGUID = Replace(getGUID, "y", Hex(Rnd() And &H3 Or &H8))
Dim i As Long: For i = 1 To 30
getGUID = Replace(getGUID, "x", Hex$(Int(Rnd() * 16)), 1, 1)
Next
End Function

Same same for german Excel version:
=VERKETTEN(DEZINHEX(ZUFALLSBEREICH(0;4294967295);8);"-";DEZINHEX(ZUFALLSBEREICH(0;65535);4);"-";DEZINHEX(ZUFALLSBEREICH(16384;20479);4);"-";DEZINHEX(ZUFALLSBEREICH(32768;49151);4);"-";DEZINHEX(ZUFALLSBEREICH(0;65535);4);DEZINHEX(ZUFALLSBEREICH(0;4294967295);8))

Since windows update taken out "Scriptlet.TypeLib", try the following:
Declare Function CoCreateGuid Lib "ole32" (ByRef GUID As Byte) As Long
Public Function GenerateGUID() As String
Dim ID(0 To 15) As Byte
Dim N As Long
Dim GUID As String
Dim Res As Long
Res = CoCreateGuid(ID(0))
For N = 0 To 15
GUID = GUID & IIf(ID(N) < 16, "0", "") & Hex$(ID(N))
If Len(GUID) = 8 Or Len(GUID) = 13 Or Len(GUID) = 18 Or Len(GUID) = 23 Then
GUID = GUID & "-"
End If
Next N
GenerateGUID = GUID
End Function
Alternatively,
if you are connecting to SQL Server 2008 or higher, try to use the SQL NEWID() function instead.

I created a VBA function that works both on mac and windows:
https://github.com/Martin-Carlsson/Business-Intelligence-Goodies/blob/master/Excel/GenerateGiud/GenerateGiud.bas
'Generates a guid, works on both mac and windows
Function Guid() As String
Guid = RandomHex(3) + "-" + _
RandomHex(2) + "-" + _
RandomHex(2) + "-" + _
RandomHex(2) + "-" + _
RandomHex(6)
End Function
'From: https://www.mrexcel.com/forum/excel-questions/301472-need-help-generate-hexadecimal-codes-randomly.html#post1479527
Private Function RandomHex(lngCharLength As Long)
Dim i As Long
Randomize
For i = 1 To lngCharLength
RandomHex = RandomHex & Right$("0" & Hex(Rnd() * 256), 2)
Next
End Function

I recently ran into problems using CreateObject("Scriptlet.TypeLib") in some vba code.
So based on NekojiruSou excel functions wrote the following which should work without any specific excel functions. This can be used to develop a user defined function in excel.
Public Function Get_NewGUID() As String
'Returns GUID as string 36 characters long
Randomize
Dim r1a As Long
Dim r1b As Long
Dim r2 As Long
Dim r3 As Long
Dim r4 As Long
Dim r5a As Long
Dim r5b As Long
Dim r5c As Long
'randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound
r1a = RandomBetween(0, 65535)
r1b = RandomBetween(0, 65535)
r2 = RandomBetween(0, 65535)
r3 = RandomBetween(16384, 20479)
r4 = RandomBetween(32768, 49151)
r5a = RandomBetween(0, 65535)
r5b = RandomBetween(0, 65535)
r5c = RandomBetween(0, 65535)
Get_NewGUID = (PadHex(r1a, 4) & PadHex(r1b, 4) & "-" & PadHex(r2, 4) & "-" & PadHex(r3, 4) & "-" & PadHex(r4, 4) & "-" & PadHex(r5a, 4) & PadHex(r5b, 4) & PadHex(r5c, 4))
End Function
Public Function Floor(ByVal X As Double, Optional ByVal Factor As Double = 1) As Double
'From: http://www.tek-tips.com/faqs.cfm?fid=5031
' X is the value you want to round
' Factor is the multiple to which you want to round
Floor = Int(X / Factor) * Factor
End Function
Public Function RandomBetween(ByVal StartRange As Long, ByVal EndRange As Long) As Long
'Based on https://msdn.microsoft.com/en-us/library/f7s023d2(v=vs.90).aspx
' randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound
RandomBetween = CLng(Floor((EndRange - StartRange + 1) * Rnd())) + StartRange
End Function
Public Function PadLeft(text As Variant, totalLength As Integer, padCharacter As String) As String
'Based on https://stackoverflow.com/questions/12060347/any-method-equivalent-to-padleft-padright
' with a little more checking of inputs
Dim s As String
Dim inputLength As Integer
s = CStr(text)
inputLength = Len(s)
If padCharacter = "" Then
padCharacter = " "
ElseIf Len(padCharacter) > 1 Then
padCharacter = Left(padCharacter, 1)
End If
If inputLength < totalLength Then
PadLeft = String(totalLength - inputLength, padCharacter) & s
Else
PadLeft = s
End If
End Function
Public Function PadHex(number As Long, length As Integer) As String
PadHex = PadLeft(Hex(number), 4, "0")
End Function

For generating random guids using just the Rnd() function, not using any libraries or APIs, the simplest I can think of is this:
' UUID Version 4 (random)
Function GetUUID4()
Dim guid As String
Dim i As Integer
Dim r As Integer
guid = ""
Randomize
For i = 0 To 31
' random digit 0..15
r = Rnd() * 15
' add dash separators
If (i = 8) Or (i = 12) Or (i = 16) Or (i = 20) Then guid = guid & "-"
' uuid4 version info in 12th and 16th digits
If (i = 12) Then r = 4
If (i = 16) Then r = (r And 3 Or 8)
' add as hex digit
guid = guid & Hex(r)
Next i
GetUUID4 = guid
End Function

If you are inserting records into a database you can use this way to make a GUID.
It is probably the most simplest and easiest way to implement as you don't need a complex VBA function as you use the built in SQL function.
The statement uses NewID(),
The syntax is as follows,
INSERT INTO table_name (ID,Column1,Column2,Column3)
VALUES (NewID(),value1,value2,value3)
In VBA syntax it is as follows,
strSql = "INSERT INTO table_name " _
& "(ID,Column1,Column2,Column3) " _
& "VALUES (NewID(),value1,value2,value3)"
And if you need to concatenate values, just treat it as a string and concatenate as you would normally for a SQL statement,
strSql = "INSERT INTO table_name " _
& "(ID,Column1,Column2,Column3) " _
& "VALUES (" & "NewID()" & "," & "value1" & "," & "value2" & "," & "value3" & ")"

Function funGetGuid() As String
Const URL As String = "http://www.guidgen.com/"
Const strMask As String = "value="
Dim l As Long
Dim txt As String
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", URL, False
.send
txt = .responseText
End With
Do
l = InStr(l + 1, txt, strMask)
If l = 0 Then Exit Do
funGetGuid = Mid$(txt, l + Len(strMask) + 1, 36)
Loop
End Function

Related

How to use the Compute to calculate the total with Double Datatype

I have expression string:
dim str as string = "999999999 * 999999999"
I use DataTable.Compute to calculate:
dim dt as new datatable
dim result as double = 0
result = cdbl(dt.Compute(str))
And I get an error:
Value is either too large or too small for Type 'Int32'.
How can I control result datatype in this case?
Solution:
This function work like Windows's Calculator. Code so confuse but it work :)
'input = "999,999,999 x 888,888,888 + 112,365 ÷ 15 − 987,653"
Public Shared Function strCalc(ByVal input As String) As String
If input.Substring(input.Length - 1, 1) = " " Then input = input.Substring(0, input.Length - 3)
input = input.Replace("−", "-").Replace("x", "*").Replace("÷", "/").Replace(",", "")
Dim temp As Double = 0
Dim arr() As String = input.Split(" ")
If arr.Length > 1 Then
temp = New DataTable().Compute(If(arr(0).Contains("."), arr(0), arr(0) & ".0") & " " & arr(1) & " " &
If(arr(2).Contains("."), arr(2), arr(2) & ".0"), "")
If arr.Length > 3 Then
For i As Integer = 3 To arr.Length - 1 Step 2
temp = New DataTable().Compute(temp & " " & arr(i) & " " &
If(arr(i + 1).Contains("."), arr(i + 1), arr(i + 1) & ".0"), "")
Next
End If
Return temp
End If
Return input
End Function
Runtime is treating your expression 999999999 * 999999999 as a multiplication of two integer values, and trying to return it as an object which is the return type of Compute API. The output of multiplication of those numbers is resulting in a very large value which is crossing the maximum value which can be stored in a variable of int (System.Int32) data type.
It results in arithmetic overflow exception. To give a hint to the runtime so that it considers the expression as a multiplication of two double numbers please use following code:
dim str as string = "999999999.0 * 999999999.0"

Array affected after sending it to a function

I send an arrey with the length of 26 twice to a function like this:
....
SaveXML strXmlItem, DFCCM, SCTM, Zieltabelle
SaveXML strXmlItem, DFCCS, SCTS, Zieltabelle
....
After the first invokation:
SaveXML strXmlItem, DFCCM, SCTM, Zieltabelle
Content of strXmlItem are changed. This array with other variablesis definedlike this:
Dim strSql, strXmlItem(), strA2l, strHex As String
and the function is:
Private Function SaveXML(strarr(), DFCC As String, SCT As String, ByVal Zieltabelle As String)
strarr(4) = DFCC
strarr(6) = SCT
For K = 0 To UBound(strarr)
MsgBox strarr(K)
Next K
'XML-Syntax anpassen
For J = 1 To conAnzahlFelder - 1
strarr(J) = MakeQuotes(strarr(J)) & ", "
Next J
strarr(conAnzahlFelder) = MakeQuotes(strarr(conAnzahlFelder)) & ")"
' Anfügeabfrage zusammenbasteln
strSql = "Insert Into " & Zieltabelle & " ("
For J = 1 To conAnzahlFelder
strSql = strSql & "f" & Trim(CStr(J - 1)) & ", "
Next J
strSql = strSql & "f" & Trim(CStr(conAnzahlFelder)) & ") "
strSql = strSql & "Values ("
For J = 1 To conAnzahlFelder + 1
strSql = strSql & strarr(J - 1)
Next J
MsgBox strSql
DoCmd.RunSQL strSql
End Function
How can I solve the problem?
there are a lot of issues in your code. But to answer your question
first:
try:
Private Function SaveXML(ByVal strarr(), DFCC As String, SCT As String, ByVal Zieltabelle As String)
instead of
Private Function SaveXML(strarr(), DFCC As String, SCT As String, ByVal Zieltabelle As String)
Google for the difference between ByVal and ByRef.
Second:
you really should use Option Explicit on the beginning of each module. You use a lot of undeclared variables. This can cause additional issues.
Third:
Dim strSql, strXmlItem(), strA2l, strHex As String
generates only ONE string variable (strHex). The others are declared as Variant if you use that Syntax. This works in some other languages but not in VBA!
and last but not least:
you declare a Function but you do not return any value for it. Either you do not want to return something (then you shouldn't declare it as Function) or you should provide a return value.

Error: A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

I'm working on a simple Matching Algorithm. I'm quite new to programming and don't quite understand the error im getting.
The File.txt contains data in this format (without the spaces between each line):
5,Name,9,9,9,9
4,Name,4,8,0,3
3,Name,4,7,3,5
2,Name,3,5,6,3
1,Name,5,8,2,9
0,Name,2,5,3,2
"A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Integer' is not valid."
The error occures for "CustomNrOld = splits(0)" and I don't see why.
Would be happy about any kind of help!!
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CustomNrNew As Integer
Dim NameIDnew As String
Dim Alphanew As Integer
Dim Betanew As Integer
Dim Gammanew As Integer
Dim Deltanew As Integer
Dim CustomNrOld As Integer
Dim NameIDold As String
Dim Alphaold As Integer
Dim Betaold As Integer
Dim Gammaold As Integer
Dim Deltaold As Integer
Dim R1 As Integer
Dim R2 As Integer
Dim R3 As Integer
Dim R4 As Integer
Using sr As New StreamReader("C:\\Users\\Paul\\Documents\\Weever\\file.txt")
Dim splits As String() = sr.ReadLine.Split(","c)
CustomNrNew = splits(0)
NameIDnew = splits(1)
Alphanew = splits(2)
Betanew = splits(3)
Gammanew = splits(4)
Deltanew = splits(5)
End Using
Using sr As New StreamReader("C:\\Users\\Paul\\Documents\\Weever\\file.txt")
sr.ReadLine()
Do While Not sr.EndOfStream
Dim splits As String() = sr.ReadLine.Split(","c)
CustomNrOld = splits(0)
NameIDold = splits(1)
Alphaold = splits(2)
Betaold = splits(3)
Gammaold = splits(4)
Deltaold = splits(5)
If Alphanew >= Alphaold = True Then
R1 = (Alphaold / Alphanew) * 100
Else
R1 = (Alphanew / Alphaold) * 100
End If
If Betanew >= Betaold = True Then
R2 = (Betaold / Betanew) * 100
Else
R2 = (Betanew / Betaold) * 100
End If
If Gammanew >= Gammaold = True Then
R3 = (Gammaold / Gammanew) * 100
Else
R3 = (Gammanew / Gammaold) * 100
End If
If Deltanew >= Deltaold = True Then
R4 = (Deltaold / Deltanew) * 100
Else
R4 = (Deltanew / Deltaold) * 100
End If
Dim Result As Integer
Result = ((R1 + R2 + R3 + R4) / 4)
My.Computer.FileSystem.WriteAllText("C:\\Users\\Paul\\Documents\\Weever\\" & NameIDnew & ".txt",
Result & "%" & " - " & NameIDold & " " & R1 & "% / " & R2 & "% / " & R3 & "% / " & R4 & "% " & Environment.NewLine, True)
My.Computer.FileSystem.WriteAllText("C:\\Users\\Paul\\Documents\\Weever\\" & NameIDold & ".txt",
Result & "%" & " - " & NameIDnew & " " & R1 & "% / " & R2 & "% / " & R3 & "% / " & R4 & "% " & Environment.NewLine, True)
Loop
End Using
Anywhere you are referencing something in splits() and you want it to be in an Integer variable, you'll need to convert your string to an integer (that's what the error is telling you).
For example: CustomNrNew = splits(0)
In this code you're trying to assign a String value (splits is an array of Strings) into an Integer (CustomNrNew). You can't convert a string directly to an integer, so you're getting an error.
To convert the string value to an integer, try using CustomNrNew = Convert.ToInt32(splits(0)) (and replace '0' with whichever value you're using on each line).
you declared splits as a bucket of strings
and then tried to put an string in an integer
CustomNrOld = Convert.ToInt32(splits(0));
will solve your problem

Getting substrings between commas. Why Mid(string,integer,integer) is failing?

I have a textbox (DropDownList1) that contains a string of 46 characters following this format:
(string1,string2,string3)
I want to get string values without the commas, this way:
a=string1
b=string2
c=string3
So I used the below code:
Dim a As String
Dim b As String
Dim c As String
Dim x As Integer = InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1
Dim y As Integer = InStr(InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, DropDownList1.Text, ",") - 1
Dim z As Integer = Len(DropDownList1.Text)
a = Mid(DropDownList1.Text, 1, InStr(1, DropDownList1.Text, ",", CompareMethod.Text) - 1)
b = Mid(DropDownList1.Text, x, y) _
'InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, _
'InStr(InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, DropDownList1.Text, ",") - 1)
c = Mid(DropDownList1.Text, _
InStr(InStr(1, DropDownList1.Text, ",", CompareMethod.Text) + 1, DropDownList1.Text, ",") + 1, _
Len(DropDownList1.Text))
However, when I debug it happens:
x=18 (which is correct with the string I was using)
y=42 (correct too)
z=46 (correct)
a=string1 (yes!)
c=string3 (yes again!)
and b=string2,string3 ----->what happened here?
Can you please tell what is wrong with my code? I simply don't get it
Assuming x,y, and z are just for debugging, and it's really a,b, and c that you care about, and that there are no commas or parenthese in the important parts of your string:
Dim values = DropDownList1.Text.Replace("(","").Replace(")","").Split(","c)
Dim a as String = values(0)
Dim b As String = values(1)
Dim c As String = values(2)
Use the Split() function on the string, applying it to some string array variable, and then assigning the values to your variables as needed if you still want to.
If in fact you're using VB.NET you can use the Split function.
Dim text As String = "a,b,c"
Dim parts As String() = text.Split(CChar(","))
Dim a As String = parts(0)
Dim b As String = parts(1)
Dim c As String = parts(2)
Give this a try...
Private Sub ParseMyString()
Dim TargetString() As String = Split("string1,string2,string3", ",")
Dim Count As Integer = 0
Dim Result As String
Const ASC_OFFSET As Integer = 97
Result = ""
Do Until Count > UBound(TargetString)
Result = Result & Chr(ASC_OFFSET + Count) & "=" & TargetString(Count) & vbCrLf
Count = Count + 1
Loop
MsgBox(Result)
End Sub

Is there a write counterpart to Microsoft.VisualBasic.FileIO.TextFieldParser?

I need to create a new CSV file. Writing my own routine wouldn't be a big task, but is there a routine in the Base Class Library for this?
Here is the function you can use to generate a row of CSV file from string list (IEnumerable(Of String) or string array can be used as well):
Function CreateCSVRow(strArray As List(Of String)) As String
Dim csvCols As New List(Of String)
Dim csvValue As String
Dim needQuotes As Boolean
For i As Integer = 0 To strArray.Count() - 1
csvValue = strArray(i)
needQuotes = (csvValue.IndexOf(",", StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf("""", StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf(vbCrLf, StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf(" ", StringComparison.InvariantCulture) = 0 _
OrElse csvValue.IndexOf(" ", StringComparison.InvariantCulture) = csvValue.Length-1)
csvValue = csvValue.Replace("""", """""")
csvCols.Add(If(needQuotes, """" & csvValue & """", csvValue))
Next
Return String.Join(",", csvCols.ToArray())
End Function
Not in the framework, the code is too simple. Trivially done with StreamWriter.Write(), you only need to do a wee bit of lifting to properly quote a string. It takes just a handful of lines:
Module CsvWriter
Public Sub WriteCsvLine(ByVal out As System.IO.TextWriter, ByVal ParamArray Values() As Object)
For ix As Integer = 0 To Values.Length - 1
If ix > 0 Then out.Write(",")
If TypeOf (Values(ix)) Is String Then
out.Write("""" + CStr(Values(ix)).Replace("""", """""") + """")
Else
out.Write(Values(ix).ToString())
End If
Next
out.WriteLine()
End Sub
End Module