Simplest way to convert a number list to a readable string in VBA -


given array of numbers:

[1,3,4,5,8,9,11]

what's simplest way in vba convert list readable string, e.g:

1, 3-5, 8-9, 11

i rewrite vb.net function vba it's quite long winded , end longer in vba.

public shared function groupednumbers(nums list(of long))      if nums nothing orelse nums.count = 0 return "-"      if nums.count = 1 return nums(0)      dim lnums = nums.distinct().orderby(function(m) m).tolist      dim curpos long = 1     dim lastnum long = lnums(0)     dim long = 0     dim numstr string = lnums(0)     dim isgap boolean = false      until >= lnums.count - 1         until >= lnums.count - 1 orelse lnums(i) + 1 <> lnums(i + 1)             += 1             isgap = true         loop         if isgap             numstr += "-" & lnums(i)         end if         if <> lnums.count - 1             numstr += ", " & lnums(i + 1)             isgap = false             += 1         end if     loop      return numstr  end function 

just wondering if has better way of doing before go rewriting vba?

if want simple method, might use following:

function groupednumbers(nums() long) string     sortme (nums) 'no built-in sort method in vba,                   'so need implement 1 (see links below).     dim numstr string     numstr = nums(0)     = 1 ubound(nums)         if nums(i) = nums(i - 1) + 1             numstr = numstr & iif(nums(i) + 1 = nums(i + 1), "", "-" & nums(i))         else             numstr = numstr & ", " & nums(i)         end if     next     groupednumbers = numstr end function 

for array sorting might refer this question.

and if want more simple, check this answer use .net version of arraylist sorting. hence need adapt above function work arraylist instead of array.

hope helps :)


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -