VBA – Insert a dash between odd numbers
In the current article, I will present the way to calculate the number of chars in a string with VBA. The inspiration came from the entry exam forHackBulgaria Programming 101v3. The tasks were given some months ago, so I assume it is OK to publish my solutions for them.
The previous task is resolved with VBA here and there.
DashInsert
You have to implement a function with the following signature – dashInsert(num)
- The argument
numis of type integer. - The function should return a string
Insert dashes '-' between each two neighboring odd numbers in num.
Don’t count zero as an odd number.
You can use any language you know.
Examples:
“9-9-946“
dashInsert(56730)
“567-30“
Here the task took me a little more time. I have used two loops – one to determine the number of dashes to be inserted and one to insert them. Furthermore, a function IsOdd was created, checking whether a digit is odd. Pretty much, it works flawlessly:
And here comes the code:
Option Explicit
Option Compare Text
Public Function DashInsert(lInput As Double) As String
Dim strArray() As String
Dim sResult() As String
Dim sInput As String
Dim lCount As Long
Dim lResultCount As Long
Dim lNumberOfDashes As Long
Dim lLoop As Long
sInput = Trim(Str(lInput))
lCount = Len(sInput)
ReDim strArray(lCount - 1)
lLoop = lCount
For lLoop = 0 To lLoop - 1
If lLoop + 1 >= lCount Then Exit For
strArray(lLoop) = Mid(sInput, lLoop + 1, 1)
strArray(lLoop + 1) = Mid(sInput, lLoop + 2, 1)
If IsOdd(strArray(lLoop)) And IsOdd(strArray(lLoop + 1)) Then
lNumberOfDashes = lNumberOfDashes + 1
End If
Next lLoop
lResultCount = lCount - 1 + lNumberOfDashes
ReDim sResult(lResultCount)
lNumberOfDashes = 0
For lLoop = 0 To lLoop
strArray(lLoop) = Mid(sInput, lLoop + 1, 1)
If lLoop = lCount - 1 Then
sResult(lLoop + lNumberOfDashes) = strArray(lLoop)
Exit For
End If
strArray(lLoop + 1) = Mid(sInput, lLoop + 2, 1)
sResult(lLoop + lNumberOfDashes) = strArray(lLoop)
If IsOdd(strArray(lLoop)) And IsOdd(strArray(lLoop + 1)) Then
lNumberOfDashes = lNumberOfDashes + 1
sResult(lLoop + lNumberOfDashes) = "-"
End If
Next lLoop
DashInsert = Join(sResult, "")
End Function
Public Function IsOdd(lNumber As String) As Boolean
IsOdd = CBool(CLng(lNumber) Mod 2)
End Function
Enjoy it!

