Welcome Guest ( Log In | Register )

 @import url(https://www.google.com/cse/api/branding.css); Custom Search
Menu
Content
Resources
To Do
Toolbox

Advertisment

 SplitOnCount

## Synopsis

CODE
' SplitOnCount
' http://www.utteraccess.com/wiki/SplitOnCount
' Code courtesy of UtterAccess Wiki
' Licensed under Creative Commons License
' http://creativecommons.org/licenses/by-sa/3.0/
'
' You are free to use this code in any application,
' provided this notice is left unchanged.
'
' rev  date                          brief descripton
' 1.0
'
Private Function SplitOnCount(StringToSplit As String, CountPerElement As Integer) As String()
'
'  Splits a string into an Array based on a character count interval
'  See the following example:
'
'  =SplitOnCount("this,that,othe,rthi,ng", 5)
'
'  returns an array(0 to 4) with 5 characters in each element:
'   0: this,
'   1: that,
'   2: othe,
'   3: rthi,
'   4: ng
'
' Returns an unintialized string array if count or string are invalid
'
On Error GoTo Err_Proc
'=========================
Dim ret() As String
Dim UBnd As Integer
Dim s As String
Dim i As Integer
Dim l As Long
'=========================

If CountPerElement &lt; 1 Or Len(StringToSplit) = 0 Then GoTo Exit_Proc

'use some temps and find out what the ubound of the result needs to be
l = Len(StringToSplit)
i = CountPerElement

'integer division alone doesn't quite work to give an accurate ubound
'e.g., 160 len string with 80 chars/element results in a ubound of 2
'we'll work around this by checking for a mod (remainder) of the division
'if no mod, remove one from the result.  this keeps the ubound correct...
'  160 len, 80/element = ubound 1
'  159 len, 80/element = ubound 1
'  161 len, 80/element = ubound 2
UBnd = IIf(l Mod i = 0, l \ i - 1, l \ i)

ReDim ret(0 To UBnd)

s = StringToSplit

For i = 0 To UBound(ret)
'apply the left portion of the string to the return
ret(i) = Left(s, CountPerElement)
'remove the left portion from the source and repeat
s = Mid(s, CountPerElement + 1)
Next i

'=========================
Exit_Proc:
SplitOnCount = ret
Exit Function
Err_Proc:
Err.Source = "ModuleName.SplitOnCount"
Select Case Err.Number
Case Else
MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error!"
End Select
Resume Exit_Proc
Resume
End Function

SplitOnCount by UtterAccess Wiki is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Editing and revision of the content is freely encouraged; for details, see Expected Usage.

 @import url(https://www.google.com/cse/api/branding.css); Custom Search

 This page has been accessed 1,788 times.  This page was last modified 15:24, 13 August 2015 by Jack Leach.   Disclaimers