Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

InString

Status
Not open for further replies.

wawanz

Programmer
Aug 29, 2002
62
ID
Hi everyone..

let's say I have string = "hfeiui37u298,39843u82,3084983"
and I want to get the the string between the commas...
can I do that in a single line of code?

Thanks
 
...and you'll need aryStr(1). Also, I think Split only likes to return to a Variant, so you might find that

Dim ary As Variant
Dim bitInCommas As String
ary = Split(myString, ",")
bitInCommas = CStr(ary(1))

works better. The Instr() approach (more traditional) would be something like

Dim pos1 As Long, pos2 As Long
Dim bitInCommas As String

pos1 = Instr(myString, ",")
pos2 = Instr(pos1 + 1, myString, ",")

bitInCommas = Mid(myString, pos1 + 1, pos2 - pos1 + 1)
 
Use the following function (I place it in a global subs module) to return a specific value from a comma separated string. Just pass the string of values and the number of the item you wish to return. If you pass an index that does not correspond to a position in the string, a blank string is returned. This can easily be modified to look for a separator other than a comma, and to return something else when the index is out of bounds.


Public Function GetCsvValue(strLine As String, Index As Integer) As String

Dim intAbsIndex As Integer ' Actual array position of index (1 less than # passed)
Dim strElements() As String ' Array to hold elements extracted from string
Dim strRetVal As String ' Value to be returned

intAbsIndex = Index - 1
strElements = Split(strLine, ",") ' Change "," to change separator

' Check to see if index value is valid for this array
If (intAbsIndex < LBound(strElements)) Or (intAbsIndex > UBound(strElements)) Then
strRetVal = &quot;&quot; ' Value returned when index is out of bounds
Else
strRetVal = strElements(intAbsIndex)
End If

GetCsvValue = strRetVal

End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top