In the early days of Basic (1970's when i started coding) the midStr() function used left and right positions directly rather than left and length we now use with mid(). I always found it more efficient in my mind to code using the old midStr() method, so I finally just created some code to do it. It's certainly not as efficient as mid(), and if I am dealing with lots of data I'd use mid() directly instead, but for simplicity, I do like the old way better, it's more direct to simply code rightPos rather then rightpos - leftPos + 1, and to test for null.
I also made the rightPos optional, and when not used, the length of the textin is used instead, so it will simply return the remainder of the text starting at the leftPos.
Any kind critique is welcome, thank you.
Function midStr(ByVal textin As String, _
ByVal leftPos As Long, _
Optional ByVal rightPos As Variant) As Variant
'midStr returns textin string using leftPos and rightPos (rather than num_chars).
'rightPos is optional, len(textin) is used for the rightPos when it's not otherwise defined.
On Error GoTo midStrErr
If IsMissing(rightPos) Then rightPos = Len(textin)
If rightPos < leftPos Then
midStr = vbNullString
Else
midStr = Mid(textin, leftPos, rightPos - leftPos + 1)
End If
Exit Function
midStrErr:
On Error Resume Next
midStr = CVErr(xlErrValue) '#VALUE!
End Function
midStr("Hello World", 2, 4)
returnsell
. I would have thought that it would return 2 characters. Not character 2, 3 and 4. \$\endgroup\$