SpellNum_Dollar module converting only one part, second part - vba

I wanted a visual basic in excel code to convert numbers into text. The code is already available on Microsoft site, but I wanted more specific one. So someone helped me and edited the Microsoft's code. It worked fine, but one critical problem occurred. I asked him for help but he is not responding anymore.
The problem is that if there is two parts, only the first part is written.
For example: 284,323.00 is written as "Two hundred eighty-four thousand dollars only"
877,666.00 is written as "Eight hundred seventy-seven thousand dollars only"
I want the full number to be converted into text like this : "877,666.00 > Eight hundred seventy-seven thousand six hundred sixty-six dollars only"
Can you help me correct the code?
This is the code:
Option Explicit
'Main Function
Function SpellNum_Dollar(ByVal MyNumber As Variant) As String
Dim Dollars, Cents, Temp, D
Dim DecimalPlace, Count
ReDim Place(9) As String
Place(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amount.
MyNumber = Trim(Str(MyNumber))
' Position of decimal place 0 if none.
DecimalPlace = InStr(MyNumber, ".")
' Convert Cents and set MyNumber to dollars amount.
If DecimalPlace > 0 Then
Cents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & _
"00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End If
Count = 1
Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & D
If Len(MyNumber) > 3 Then
MyNumber = Left(MyNumber, Len(MyNumber) - 3)
Else
MyNumber = ""
End If
Count = Count + 1
Loop
Select Case Dollars
Case ""
Dollars = "No Dollars"
Case "One"
Dollars = "One Dollar"
Case Else
Dollars = Dollars & " Dollars"
End Select
Select Case Cents
Case ""
Cents = ""
Case "One"
Cents = " and One Cent"
Case Else
Cents = " and " & Cents & " Cents"
End Select
SpellNum_Dollar = LowerCaseWords(Dollars & Cents)
End Function
' Converts a number from 100-999 into text
Function GetHundreds(ByVal MyNumber)
Dim Result As String
If Val(MyNumber) = 0 Then Exit Function
MyNumber = Right("000" & MyNumber, 3)
' Convert the hundreds place.
If Mid(MyNumber, 1, 1) <> "0" Then
Result = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "
End If
' Convert the tens and ones place.
If Mid(MyNumber, 2, 1) <> "0" Then
Result = Result & GetTens(Mid(MyNumber, 2))
Else
Result = Result & GetDigit(Mid(MyNumber, 3))
End If
GetHundreds = Result
End Function
' Converts a number from 10 to 99 into text.
Function GetTens(TensText)
Dim Result As String
Result = "" ' Null out the temporary function value.
If Val(Left(TensText, 1)) = 1 Then ' If value between 10-19...
Select Case Val(TensText)
Case 10: Result = "Ten"
Case 11: Result = "Eleven"
Case 12: Result = "Twelve"
Case 13: Result = "Thirteen"
Case 14: Result = "Fourteen"
Case 15: Result = "Fifteen"
Case 16: Result = "Sixteen"
Case 17: Result = "Seventeen"
Case 18: Result = "Eighteen"
Case 19: Result = "Nineteen"
Case Else
End Select
Else ' If value between 20-99...
Select Case Val(Left(TensText, 1))
Case 2: Result = "Twenty-"
Case 3: Result = "Thirty-"
Case 4: Result = "Forty-"
Case 5: Result = "Fifty-"
Case 6: Result = "Sixty-"
Case 7: Result = "Seventy-"
Case 8: Result = "Eighty-"
Case 9: Result = "Ninety-"
Case Else
End Select
Result = Result & GetDigit _
(Right(TensText, 1)) ' Retrieve ones place.
End If
If Right(Result, 1) = "-" Then
Result = Left(Result, Len(Result) - 1)
End If
GetTens = Result
End Function
' Converts a number from 1 to 9 into text.
Function GetDigit(Digit)
Select Case Val(Digit)
Case 1: GetDigit = "One"
Case 2: GetDigit = "Two"
Case 3: GetDigit = "Three"
Case 4: GetDigit = "Four"
Case 5: GetDigit = "Five"
Case 6: GetDigit = "Six"
Case 7: GetDigit = "Seven"
Case 8: GetDigit = "Eight"
Case 9: GetDigit = "Nine"
Case Else: GetDigit = ""
End Select
End Function
Function LowerCaseWords(MyNumber As String) As String
'Splits the number into an array and then loops through the array, starting at the second word, and lower cases all of them
'Just need to check if the first word has a dash, if so, the first letter after the dash will be lower cased
Const ArrayLoopStart As Long = 1
Dim WordArray As Variant
Dim WordCounter As Long
Dim FindDash As Long
WordArray = Split(MyNumber, " ")
FindDash = InStr(1, WordArray(0), "-")
If FindDash > 0 Then
WordArray(0) = Left(WordArray(0), FindDash) & LCase(Mid(WordArray(0), FindDash + 1, 1)) & Right(WordArray(0), Len(WordArray(0)) - 1 - FindDash)
End If
For WordCounter = ArrayLoopStart To UBound(WordArray)
WordArray(WordCounter) = LCase(WordArray(WordCounter))
Next WordCounter
LowerCaseWords = Join(WordArray, " ")
End Function

Related

How can I extract the 'logical_test' from an if statement in excel?

I'm putting together an excel spreadsheet for calculations, and I need to be able to show the formulas to go with the decisions, for the most part its pretty straight forward, but When I come to an 'if' formula in an excel cell, I don't want to show the value_if_true and value_if_false... Just the logical_test value.
Example:
Formula is: =if(and(5<=A1, A1<=10),"Pass", "Fail");
Result will be: "and(5<=A1, A1<=10)"
I need to be able to work with complex logical tests which may include nested if statements, so just splitting at the commas won't work reliably. Similarly the value_if_true and value_if_false statements could also contain if statements.
Any ideas?
If have clear understanding of what you asking for, then you can use something like this (shall be used only with IF() statement :
Function extrIf(ByVal ifstatement As Range) As String
Dim S$, sRev$, x%, k
S = Replace(Replace(ifstatement.Formula, "IF(", "\"), "),", ")|")
sRev = StrReverse(S)
If InStr(1, sRev, "|") > InStr(1, sRev, "\") Or InStr(1, sRev, "|") = 0 Then
x = InStr(1, StrReverse(Left(sRev, InStr(1, sRev, "\"))), ",") - 1
S = Mid(S, 1, Len(S) - InStr(1, sRev, "\") + x) & "|"
End If
sRev = ""
For Each k In Split(S, "|")
If k <> "" Then
If k Like "*\*" Then
sRev = sRev & ", " & Mid(k, InStr(1, k, "\") + 1, 999)
End If
End If
Next
extrIf = Mid(sRev, 3, 999)
End Function
example:
test:
Maybe this is not complete solution for you, but I think it might give you right direction.
If the cell formula starts with an If statement then you can return the logic test (starting after the first open parenthesis) by determining the position of the first comma where the sum of the previous open parenthesis - the sum previous closed = 0.
Formulas
Function ExtractIfTest(Target As Range) As String
Dim ch As String, s As String
Dim openP As Long
Dim x As Long
s = Target.formula
For x = 5 To Len(s)
ch = Mid(s, x, 1)
If Mid(s, x, 1) = "(" Then
openP = openP + 1
ElseIf Mid(s, x, 1) = ")" Then
openP = openP - 1
ElseIf Mid(s, x, 1) = "," And openP = 0 Then
ExtractIfTest = Mid(s, 5, x - 12)
End If
Next
End Function
Results
There might be instances where the is a comma without parenthesis A1,B1. If this happens simple escape them with parenthesis (A1,B1)
I've written an UDF that extract any of the parameters of the target formula. It's close to the one in Thomas answer, but more global and takes into account strings that can enclose commas or parenthesis.
Function ExtractFormulaParameter(Target As Range, Optional Position As Long = 1) As Variant
Dim inString As Boolean
Dim formula As String
Dim st As Long, sp As Long, i As Long, c As String
Dim parenthesis As Long, comma As Long
formula = Target.formula
st = 0: sp = 0
If Position <= 0 Then ExtractFormulaParameter = CVErr(xlErrValue): Exit Function
For i = 1 To Len(formula)
c = Mid$(formula, i, 1)
If inString Then
If c = """" Then
inString = False
End If
Else
Select Case c
Case """"
inString = True
Case "("
parenthesis = parenthesis + 1
If parenthesis = 1 And Position = 1 Then
st = i + 1
End If
Case ")"
parenthesis = parenthesis - 1
If parenthesis = 0 And sp = 0 Then sp = i: Exit For
Case ","
If parenthesis = 1 Then
comma = comma + 1
If Position = 1 And comma = 1 Then sp = i: Exit For
If Position > 1 And comma = Position - 1 Then st = i + 1
If Position > 1 And comma = Position Then sp = i: Exit For
End If
Case Else
End Select
End If
Next i
If st = 0 Or sp = 0 Then
ExtractFormulaParameter = CVErr(xlErrNA)
Else
ExtractFormulaParameter = Mid$(formula, st, sp - st)
End If
End Function
By default it returns the first parameter, but you can also return the second or the third, and it should work with any formula.
Thanks for the replies all. I thought about this more, and ended up coming up with a similar solution to those posted above - essentially string manipulation to extract the text where we expect to find the logical test.
Works well enough, and I'm sure I could use it to extract further logical tests from substrings too.

Converting Check Amount To Words Using Case/Methods

I am working on a project for my Visual Basic class, which is to create a digital check. The assignment requires us to input a check amount, which translates into words. In example, $1,200.00 needs to output "One thousand two hundred dollars"
For the most part, my code works. I'm using a switch statement. The original assignment was to have our check go up to a 9,999 value, but as we continue to build, we need to be able to convert up to 99,999.
As I said, I've been using a series of case statements, but realize that this is a very "hard code" way of doing this and would like create a method that can check these type of things for me, however I'm still new to Visual Basic and don't really have a good idea where to start or what is applicable in this scenario (we don't really have an example to go by.)
Here is my WriteCheck method that does the assigning/converting for the most part.
'Convert check value from a text field to a double'
Try
checkValue = checkInput.Text
Catch ex As InvalidCastException
MessageBox.Show("You must enter a numbers to write a check.")
End Try
'Operation to convert number to String'
thousands = checkValue \ 1000
hundreds = checkValue Mod 1000
hundreds = hundreds \ 100
tens = checkValue Mod 100
tens = tens \ 10
ones = checkValue Mod 10
ones = ones \ 1
'Case for thousands'
Select Case thousands & hundreds & tens
Case 1
tempStringT = "One"
Case 2
tempStringT = "Two"
Case 3
tempStringT = "Three"
Case 4
tempStringT = "Four"
Case 5
tempStringT = "Five"
Case 6
tempStringT = "Six"
Case 7
tempStringT = "Seven"
Case 8
tempStringT = "Eight"
Case 9
tempStringT = "Nine"
End Select
'Case for hundreds'
Select Case hundreds
Case 1
tempStringH = "one"
Case 2
tempStringH = "two"
Case 3
tempStringH = "three"
Case 4
tempStringH = "four"
Case 5
tempStringH = "five"
Case 6
tempStringH = "six"
Case 7
tempStringH = "seven"
Case 8
tempStringH = "eight"
Case 9
tempStringH = "nine"
End Select
'Case for tens'
Select Case tens Or ones
Case 1
tempStringTens = "one"
Case 2
tempStringTens = "twenty"
Case 3
tempStringTens = "thirty"
Case 4
tempStringTens = "fourty"
Case 5
tempStringTens = "fifty"
Case 6
tempStringTens = "sixty"
Case 7
tempStringTens = "seventy"
Case 8
tempStringTens = "eighty"
Case 9
tempStringTens = "ninety"
End Select
If tempStringTens <> "one" Then
'Case for ones'
Select Case ones
Case 1
tempStringO = "one"
Case 2
tempStringO = "two"
Case 3
tempStringO = "three"
Case 4
tempStringO = "four"
Case 5
tempStringO = "five"
Case 6
tempStringO = "six"
Case 7
tempStringO = "seven"
Case 8
tempStringO = "eight"
Case 9
tempStringO = "nine"
End Select
lblConverted.Text = tempStringT & " thousand " & tempStringH & " hundred " & tempStringTens & " " & tempStringO & " dollars " & change & "/100"
End If
If tempStringTens = "one" Then
Select Case ones
Case 1
tempStringO = "eleven"
Case 2
tempStringO = "twelve"
Case 3
tempStringO = "thirteen"
Case 4
tempStringO = "fourteen"
Case 5
tempStringO = "fifteen"
Case 6
tempStringO = "sixteen"
Case 7
tempStringO = "seventeen"
Case 8
tempStringO = "eighteen"
Case 9
tempStringO = "nineteen"
End Select
lblConverted.Text = tempStringT & " thousand " & tempStringH & " hundred " & tempStringO & " dollars"
End If
End Sub
This is my approach to the problem. The solution can be easily scaled up or down by adding or removing items in BigNumbers and upping the scope of num beyond Long if necessary. (As written, it will work for numbers up to 999,999,999,999,999.)
Public Function NumberToText(ByVal num As Long) As String
Dim BigNumbers() As String = {"", " Thousand", " Million", " Billion", " Trillion"}
Dim TextParts() As String = {}
If num < 0 Then
Return "Checks cannot be written for negative amounts."
ElseIf num >= 10 ^ ((BigNumbers.Length) * 3) Then
Return "This number exceeds the current maximum value of " & NumberToText(10 ^ ((BigNumbers.Length) * 3) - 1) & "."
End If
Dim LoopCount As Integer = 0
While num >= 1000
ReDim Preserve TextParts(TextParts.Length)
If num Mod 1000 > 0 Then
TextParts(TextParts.GetUpperBound(0)) = ThreeDigitText(num Mod 1000) & BigNumbers(LoopCount)
End If
num = num \ 1000
LoopCount += 1
End While
ReDim Preserve TextParts(TextParts.Length)
TextParts(TextParts.GetUpperBound(0)) = ThreeDigitText(num) & BigNumbers(LoopCount)
If Array.IndexOf(TextParts, "Error") > -1 Then
Return "An unknown error occurred while converting this number to text."
Else
Array.Reverse(TextParts)
Return Join(TextParts)
End If
End Function
Private Function ThreeDigitText(ByVal num As Integer) As String
If num > 999 Or num < 0 Then
Return "Error"
Else
Dim h As Integer = num \ 100 'Hundreds place
Dim tempText As String = ""
If h > 0 Then
tempText = OneDigitText(h) & " Hundred"
End If
num -= h * 100
If num > 0 And Not tempText = "" Then
tempText &= " "
End If
If num > 9 And num < 20 Then
Dim DoubleDigits() As String = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
Return tempText & DoubleDigits(num - 10)
Else
Dim TensPlace() As String = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
Dim t As Integer = num \ 10 'Tens place
num -= t * 10
If t > 1 Then
tempText &= TensPlace(t - 2)
If num > 0 Then
tempText &= " "
End If
End If
If num > 0 Then
tempText &= OneDigitText(num)
End If
Return tempText
End If
End If
End Function
Private Function OneDigitText(ByVal num As Integer) As String
If num > 9 Or Num < 0 Then
Return "Error"
Else
Dim SingleDigits() As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Return SingleDigits(num)
End If
End Function
Since this is for school, you will probably want to adapt parts of my code to your own rather than copy the whole thing. (Teachers can usually tell when you get code off the internet, especially if you can't explain every line.) If you have any questions about it, send them to the email listed in my profile.

Need help converting a number to words

I am trying to convert a number to a word from a RDLC report:
Public Shared Function changeToWords(ByVal numb As [String]) As [String]
Dim val As [String] = ""
Dim wholeNo As [String] = numb
Dim points As [String] = ""
Dim andStr As [String] = ""
Dim pointStr As [String] = ""
Dim endStr As [String] = ""
Try
Dim decimalPlace As Integer = numb.IndexOf(".")
If decimalPlace > 0 Then
wholeNo = numb.Substring(0, decimalPlace)
points = numb.Substring(decimalPlace + 1)
If Convert.ToInt32(points) > 0 Then
andStr = "point"
' just to separate whole numbers from points
pointStr = translateCents(points)
End If
End If
val = [String].Format("{0} {1}{2} {3}", translateWholeNumber(wholeNo).Trim(), andStr, pointStr, endStr)
Catch
End Try
Return val
End Function
Private Shared Function translateWholeNumber(ByVal number As [String]) As [String]
Dim word As String = ""
Try
Dim beginsZero As Boolean = False
'tests for 0XX
Dim isDone As Boolean = False
'test if already translated
Dim dblAmt As Double = (Convert.ToDouble(number))
'if ((dblAmt > 0) && number.StartsWith("0"))
If dblAmt > 0 Then
'test for zero or digit zero in a nuemric
beginsZero = number.StartsWith("0")
Dim numDigits As Integer = number.Length
Dim pos As Integer = 0
'store digit grouping
Dim place As [String] = ""
'digit grouping name:hundres,thousand,etc...
Select Case numDigits
Case 1
'ones' range
word = ones(number)
isDone = True
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 2
'tens' range
word = tens(number)
isDone = True
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 3
'hundreds' range
pos = (numDigits Mod 3) + 1
place = " Hundred "
Exit Select
' TODO: might not be correct. Was : Exit Select
'thousands' range
Case 4, 5, 6
pos = (numDigits Mod 4) + 1
place = " Thousand "
Exit Select
' TODO: might not be correct. Was : Exit Select
'millions' range
Case 7, 8, 9
pos = (numDigits Mod 7) + 1
place = " Million "
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 10
'Billions's range
pos = (numDigits Mod 10) + 1
place = " Billion "
Exit Select
Case Else
' TODO: might not be correct. Was : Exit Select
'add extra case options for anything above Billion...
isDone = True
Exit Select
' TODO: might not be correct. Was : Exit Select
End Select
If Not isDone Then
'if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos))
'check for trailing zeros
If beginsZero Then
word = " and " & word.Trim()
End If
End If
'ignore digit grouping names
If word.Trim().Equals(place.Trim()) Then
word = ""
End If
End If
Catch
End Try
Return word.Trim()
End Function
Private Shared Function tens(ByVal digit As [String]) As [String]
Dim digt As Integer = Convert.ToInt32(digit)
Dim name As [String] = Nothing
Select Case digt
Case 10
name = "Ten"
Exit Select
' TODO: might not be correct. Was : Exit Select \
Case 11
name = "Eleven"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 12
name = "Twelve"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 13
name = "Thirteen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 14
name = "Fourteen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 15
name = "Fifteen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 16
name = "Sixteen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 17
name = "Seventeen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 18
name = "Eighteen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 19
name = "Nineteen"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 20
name = "Twenty"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 30
name = "Thirty"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 40
name = "Fourty"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 50
name = "Fifty"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 60
name = "Sixty"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 70
name = "Seventy"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 80
name = "Eighty"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 90
name = "Ninety"
Exit Select
Case Else
' TODO: might not be correct. Was : Exit Select
If digt > 0 Then
name = (Convert.ToString(tens(digit.Substring(0, 1) & "0")) & " ") & Convert.ToString(ones(digit.Substring(1)))
End If
Exit Select
' TODO: might not be correct. Was : Exit Select
End Select
Return name
End Function
Private Shared Function ones(ByVal digit As [String]) As [String]
Dim digt As Integer = Convert.ToInt32(digit)
Dim name As [String] = ""
Select Case digt
Case 1
name = "One"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 2
name = "Two"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 3
name = "Three"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 4
name = "Four"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 5
name = "Five"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 6
name = "Six"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 7
name = "Seven"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 8
name = "Eight"
Exit Select
' TODO: might not be correct. Was : Exit Select
Case 9
name = "Nine"
Exit Select
' TODO: might not be correct. Was : Exit Select
End Select
Return name
End Function
Private Shared Function translateCents(ByVal cents As [String]) As [String]
Dim cts As [String] = ""
Dim digit As [String] = ""
Dim engOne As [String] = ""
For i As Integer = 0 To cents.Length - 1
digit = cents(i).ToString()
If digit.Equals("0") Then
engOne = "Zero"
Else
engOne = ones(digit)
End If
cts += " " & engOne
Next
Return cts
End Function
I am getting the wrong output from the conversion.
For 52001 the given output is Fifty Two Thousand and Hundred One.
However, it should be Fifty Two Thousand and One.
You'll need to add a conditional statement to modify your string concatenation behavior when the beginning of your substring is a zero.
'if transalation is not done, continue...(Recursion comes in now!!)
If (number.Substring(0, 1) = "0") Then
word = translateWholeNumber(number.Substring(pos))
Else
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos))
End If
Edit: Doing this breaks output if the original string sent to changeToWords begins with any zeros. To rectify that condition, you can trim leading zeros, before the string is processed:
Dim wholeNo As [String] = numb.TrimStart("0"c)
Just change this line:
If Not isDone Then
'if transalation is not done, continue...(Recursion comes in now!!)
word = translateWholeNumber(number.Substring(0, pos)) + place + translateWholeNumber(number.Substring(pos))
'check for trailing zeros
If beginsZero Then
word = translateWholeNumber(number.Substring(0, pos))+ " and " + translateWholeNumber(number.Substring(pos))
End If
End If

VB select case not working as expected

I am a total novice with visual basic and teaching myself as I go along. I am building a VB in studio 2008 (I'm obliged to use this version) that logs into a device , transmits log in and password and then transmits commands read from a .txt file using reflections. All of this is working fine. The device executes the command and outputs 1 of 28 possible responses.
I am using select case to evaluate the responses and act accordingly. The device session stops as expected when EXECUTED is seen in the session window, my test data is designed so the first response I get is "EXECUTED", the weird thing is my VB "sees" the EXECUTED message (Case 1) but select case responds as if it has seen FAILED (Case 2), subsequent lines of the test data illicit different cases (5 and 6) but the response is always the next case along. I have tried Case n, case is = n, case "string value" but I get errors.
Here's my code - note that I haven't defined all 28 cases yet but the undefined ones are REM'ed out in my active version. Any ideas or suggestions would be gratefully received!
Option Explicit On
Public Class modCaseSelect
Shared Sub Dev_Responses(ByVal refl)
Dim Result As String
Dim CR = vbCr
Dim Resp As Integer
Dim Dev_Resp(28) As String
Dev_Resp(0) = "RUNNING"
Dev_Resp(1) = "EXECUTED"
Dev_Resp(2) = "FAILED"
Dev_Resp(3) = "SEMANTICS ERROR"
Dev_Resp(4) = "NONEXISTENT"
Dev_Resp(5) = "NOT FOUND"
Dev_Resp(6) = "SPECIAL"
Dev_Resp(7) = "CONFIRM: Y/N"
Dev_Resp(8) = "CONFIRM (Y/N)"
Dev_Resp(9) = "CONFIRM EXECUTION: Y/N"
Dev_Resp(10) = "ALREADY EXECUTED"
Dev_Resp(11) = ""
Dev_Resp(12) = ""
Dev_Resp(13) = ""
Dev_Resp(14) = ""
Dev_Resp(15) = ""
Dev_Resp(16) = ""
Dev_Resp(17) = ""
Dev_Resp(18) = ""
Dev_Resp(19) = ""
Dev_Resp(20) = ""
Dev_Resp(21) = ""
Dev_Resp(23) = ""
Dev_Resp(23) = ""
Dev_Resp(24) = ""
Dev_Resp(25) = ""
Dev_Resp(26) = ""
Dev_Resp(27) = ""
Dev_Resp(28) = "IN PROGRESS"
With refl
Select Case .WaitForStrings(Dev_Resp, "0:4:30") 'checkDev_Resp
Case 0 ' "RUNNING"
Result = Dev_Resp(0)
Resp = MsgBox((Dev_Resp(0) & CR & CR & Continue?"), 17, "Case 0 error")
Case 1 ' "EXECUTED"
Result = Dev_Resp(1)
Resp = MsgBox((Dev_Resp(1) & CR & CR & "Continue?"), 17, "Case 1")
Case 2 ' "FAILED"
Result = Dev_Resp(2)
Resp = MsgBox((Dev_Resp(2) & CR & CR & "Continue?"), 17, "Case 2 error")
Case 3 ' "SEMANTICS ERROR"
Result = Dev_Resp(3)
Resp = MsgBox((Dev_Resp(3) & CR & CR & "Continue?"), 17, "Case 3 error")
Case 4 ' "NONEXISTENT"
Result = Dev_Resp(4)
Resp = MsgBox((Dev_Resp(4) & CR & CR & "Continue?"), 17, "Case 4 error")
Case 5 ' "NOT FOUND"
Result = Dev_Resp(5)
Resp = MsgBox((Dev_Resp(5) & CR & CR & "Continue?"), 17, "Case 5 error")
Case 6 ' "SPECIAL"
Result = Dev_Resp(6)
Resp = MsgBox((Dev_Resp(6) & CR & CR & "Continue?"), 17, "Case 6 error")
Case 7 ' "CONFIRM: Y/N"
Result = Dev_Resp(7)
.Transmit("Y" & CR)
Case 8 ' "CONFIRM (Y/N)"
Result = Dev_Resp(8)
.Transmit("Y" & CR)
Case 9 ' "CONFIRM EXECUTION: Y/N"
Result = Dev_Resp(9)
.Transmit("Y" & CR)
Case 10 ' "ALREADY EXECUTED"
Result = Dev_Resp(10)
Resp = MsgBox((Dev_Resp(10) & CR & CR & "Continue?"), 17, "Case 10 error")
Case 11 ' ""
Result = Dev_Resp(11)
Case 12 ' ""
Result = Dev_Resp(12)
Case 13 ' ""
Result = Dev_Resp(13)
Case 14 ' ""
Result = Dev_Resp(14)
Case 15 ' ""
Result = Dev_Resp(15)
Case 16 ' ""
Result = Dev_Resp(16)
Case 17 ' ""
Result = Dev_Resp(17)
Case 18 ' ""
Result = Dev_Resp(18)
Case 19 ' ""
Result = Dev_Resp(19)
Case 20 ' ""
Result = Dev_Resp(20)
Case 21 ' ""
Result = Dev_Resp(21)
Case 22 ' ""
Result = Dev_Resp(22)
Case 23 ' ""
Result = Dev_Resp(23)
Case 24 ' ""
Result = Dev_Resp(24)
Case 25 ' ""
Result = Dev_Resp(25)
Case 26 ' ""
Result = Dev_Resp(26)
Case 27 ' ""
Result = Dev_Resp(27)
Case 28 ' "IN PROGRESS"
Result = Dev_Resp(28)
Resp = MsgBox((Dev_Resp(28) & CR & CR & "Continue?"), 17, "Case 28 error")
Case Else
End Select
End With
End Sub
End Class
You are missing a double quote " in your first Case. Try changing it to this:
Case 0 ' "RUNNING"
Result = Dev_Resp(0)
Resp = MsgBox((Dev_Resp(0) & CR & CR & "Continue?"), 17, "Case 0 error")
Notice I've added the double quote before "Continue?".
Get rid of the With statement. Create and assign a holder variable and use that with the select statement. Doing so will allow you to see what is actually getting passed into the select statement by setting a stop point in the debugger.
Dim temp_resp as integer = refl.WaitForStrings(Dev_Resp, "0:4:30")
Select Case temp_resp
'the case statements here.
End Select
Reflections WaitForStrings uses a zero-based array parameter, but it returns a 1-based index of strings. Waitforstrings sees array entry zero as the first valid entry so the first select case (Case = 1) corresponds to array entry 0.

Bitwise And with Large Numbers in VBA

I keep getting an Overflow on the bitwise and in this first function. I fixed the other overflows by converting from Long to Currency (still seems weird), but I can't get this And to work.
Any ideas? I'm just trying to convert some IP addresses to CIDRs and calculate some host numbers.
Option Explicit
Public Function ConvertMaskToCIDR(someIP As String, someMask As String)
Dim ipL As Variant
ipL = iPToNum(someIP)
Dim maskL As Variant
maskL = iPToNum(someMask)
maskL = CDec(maskL)
'Convert Mask to CIDR(1-30)
Dim oneBit As Variant
oneBit = 2147483648#
oneBit = CDec(oneBit)
Dim CIDR As Integer
CIDR = 0
Dim x As Integer
For x = 31 To 0 Step -1
If (maskL And oneBit) = oneBit Then
CIDR = CIDR + 1
Else
Exit For
End If
oneBit = oneBit / 2# 'Shift one bit to the right (>> 1)
Next
Dim answer As String
answer = numToIp(ipL And maskL) & " /" & CStr(CIDR)
End Function
Public Function NumHostsInCidr(CIDR As Integer) As Currency
Dim mask As Currency
mask = maskFromCidr(CIDR)
NumHostsInCidr = iPnumOfHosts(mask)
End Function
Private Function maskFromCidr(ByVal CIDR As Integer) As Currency
'x = 32 - CIDR
'z = (2^x)-1
'return z xor 255.255.255.255
maskFromCidr = CLng(2 ^ ((32 - CIDR)) - 1) Xor 4294967295# '255.255.255.255
End Function
Private Function iPnumOfHosts(ByVal IPmsk As Currency) As Currency 'a mask for the host portion
'255.255.255.0 XOR 255.255.255.255 = 255 so 0 to 255 is 256 hosts
iPnumOfHosts = IPmsk Xor 4294967295# '255.255.255.255 , calculate the number of hosts
End Function
Private Function numToIp(ByVal theIP As Currency) As String 'convert number back to IP
Dim IPb(3) As Byte '4 octets
Dim theBit As Integer
theBit = 31 'work MSb to LSb
Dim addr As String 'accumulator for address
Dim x As Integer
For x = 0 To 3 'four octets
Dim y As Integer
For y = 7 To 0 Step -1 '8 bits
If (theIP And CLng(2 ^ theBit)) = CLng(2 ^ theBit) Then 'if the bit is on
IPb(x) = IPb(x) + CByte(2 ^ y) 'accumulate
End If
theBit = theBit - 1
Next
addr = addr & CStr(IPb(x)) & "." 'add current octet to string
Next
numToIp = trimLast(addr, ".")
End Function
Private Function iPToNum(ByVal ip As String) As Currency
Dim IPpart As Variant
Dim IPbyte(3) As Byte
IPpart = Split(ip, ".")
Dim x As Integer
For x = 0 To 3
IPbyte(x) = CByte(IPpart(x))
Next x
iPToNum = (IPbyte(0) * (256 ^ 3)) + (IPbyte(1) * (256 ^ 2)) + (IPbyte(2) * 256#) + IPbyte(3)
End Function
Private Function trimLast(str As String, chr As String)
'****
'* Remove "chr" (if it exists) from end of "str".
'****
trimLast = str
If Right(str, 1) = chr Then trimLast = Left(str, Len(str) - 1)
End Function
Whoah,
it is definitelly interesting functionality. But I would do this in very different way. I would treat IP adress and Mask as array of four bytes. Moreover as far as I remeber (well it was some time ago) CIDR and mask can be converted to each other in very simply way (did you looked at the table?). Why don't you apply bitwise operations to each byte separatelly?
BR.
edit: ok I looked closer at the code. The reason why it is overflowing is that you can't use currency and and. I think and is internally defined as Long and can't return any bigger values. It is very common in other languages too. I remember that once I had this problem in other language (Pascal?). You can try to replace and by division. It will be slow but it can't be matter here I suppose. Other solution is, like I wrote, to treat those valueas all the time as byte arrays and perform bitwise operations on each byte.
This is an entirely mathematical approach to working with IPv4 addresses in VBA (Excel specifically).
The first three functions are serving a strictly supporting role.
Support #1:
Public Function RoundDouble(ByVal Number As Double, ByVal Places As Long) As Double
On Error GoTo Err_RoundDouble
Dim i As Long
Dim j As Long
i = 0
j = 0
While Number < -(2 ^ 14)
Number = Number + (2 ^ 14)
i = i - 1
Wend
While Number > (2 ^ 14)
Number = Number - (2 ^ 14)
i = i + 1
Wend
While Number < -(2 ^ 5)
Number = Number + (2 ^ 5)
j = j - 1
Wend
While Number > (2 ^ 5)
Number = Number - (2 ^ 5)
j = j + 1
Wend
RoundDouble = Round(Number, Places) + (i * (2 ^ 14)) + (j * (2 ^ 5))
Exit_RoundDouble:
Exit Function
Err_RoundDouble:
MsgBox Err.Description
Resume Exit_RoundDouble
End Function
Support #2:
Public Function RoundDownDouble(ByVal Number As Double, ByVal Places As Long) As Double
On Error GoTo Err_RoundDownDouble
Dim i As Double
i = RoundDouble(Number, Places)
If Number < 0 Then
If i < Number Then
RoundDownDouble = i + (10 ^ -Places)
Else
RoundDownDouble = i
End If
Else
If i > Number Then
RoundDownDouble = i - (10 ^ -Places)
Else
RoundDownDouble = i
End If
End If
Exit_RoundDownDouble:
Exit Function
Err_RoundDownDouble:
MsgBox Err.Description
Resume Exit_RoundDownDouble
End Function
Support #3
Public Function ModDouble(ByVal Number As Double, ByVal Divisor As Double) As Double
On Error GoTo Err_ModDouble
Dim rndNumber As Double
Dim rndDivisor As Double
Dim intermediate As Double
rndNumber = RoundDownDouble(Number, 0)
rndDivisor = RoundDownDouble(Divisor, 0)
intermediate = rndNumber / rndDivisor
ModDouble = (intermediate - RoundDownDouble(intermediate, 0)) * rndDivisor
Exit_ModDouble:
Exit Function
Err_ModDouble:
MsgBox Err.Description
Resume Exit_ModDouble
End Function
This first function will convert a Double back into an IP address.
Public Function NUMtoIP(ByVal Number As Double) As String
On Error GoTo Err_NUMtoIP
Dim intIPa As Double
Dim intIPb As Double
Dim intIPc As Double
Dim intIPd As Double
If Number < 0 Then Number = Number * -1
intIPa = RoundDownDouble(ModDouble(Number, (2 ^ 32)) / (2 ^ 24), 0)
intIPb = RoundDownDouble(ModDouble(Number, (2 ^ 24)) / (2 ^ 16), 0)
intIPc = RoundDownDouble(ModDouble(Number, (2 ^ 16)) / (2 ^ 8), 0)
intIPd = ModDouble(Number, (2 ^ 8))
NUMtoIP = intIPa & "." & intIPb & "." & intIPc & "." & intIPd
Exit_NUMtoIP:
Exit Function
Err_NUMtoIP:
MsgBox Err.Description
Resume Exit_NUMtoIP
End Function
This second function is strictly to convert from IPv4 dotted octet format to a Double.
Public Function IPtoNUM(ByVal IP_String As String) As Double
On Error GoTo Err_IPtoNUM
Dim intIPa As Integer
Dim intIPb As Integer
Dim intIPc As Integer
Dim intIPd As Integer
Dim DotLoc1 As Integer
Dim DotLoc2 As Integer
Dim DotLoc3 As Integer
Dim DotLoc4 As Integer
DotLoc1 = InStr(1, IP_String, ".", vbTextCompare)
DotLoc2 = InStr(DotLoc1 + 1, IP_String, ".", vbTextCompare)
DotLoc3 = InStr(DotLoc2 + 1, IP_String, ".", vbTextCompare)
DotLoc4 = InStr(DotLoc3 + 1, IP_String, ".", vbTextCompare)
If DotLoc1 > 1 And DotLoc2 > DotLoc1 + 1 And _
DotLoc3 > DotLoc2 + 1 And DotLoc4 = 0 Then
intIPa = CInt(Mid(IP_String, 1, DotLoc1))
intIPb = CInt(Mid(IP_String, DotLoc1 + 1, DotLoc2 - DotLoc1))
intIPc = CInt(Mid(IP_String, DotLoc2 + 1, DotLoc3 - DotLoc2))
intIPd = CInt(Mid(IP_String, DotLoc3 + 1, 3))
If intIPa <= 255 And intIPa >= 0 And intIPb <= 255 And intIPb >= 0 And _
intIPc <= 255 And intIPc >= 0 And intIPd <= 255 And intIPd >= 0 Then
IPtoNUM = (intIPa * (2 ^ 24)) + (intIPb * (2 ^ 16)) + _
(intIPc * (2 ^ 8)) + intIPd
Else
IPtoNUM = 0
End If
Else
IPtoNUM = 0
End If
Exit_IPtoNUM:
Exit Function
Err_IPtoNUM:
MsgBox Err.Description
Resume Exit_IPtoNUM
End Function
Next we have the conversion from an IPv4 address to it's bitmask representation (assuming that the source entry is a string containing only the dotted octet format of the subnet mask).
Public Function IPtoBitMask(ByVal strIP_Address As String) As Integer
On Error GoTo Err_IPtoBitMask
IPtoBitMask = (32 - Application.WorksheetFunction.Log((2 ^ 32 - IPtoNUM(strIP_Address)), 2))
Exit_IPtoBitMask:
Exit Function
Err_IPtoBitMask:
MsgBox Err.Description
Resume Exit_IPtoBitMask
End Function
This last one is to convert a bitmask back into dotted octet format.
Public Function BitMasktoIP(ByVal intBit_Mask As Integer) As String
On Error GoTo Err_BitMasktoIP
BitMasktoIP = NUMtoIP((2 ^ 32) - (2 ^ (32 - intBit_Mask)))
Exit_BitMasktoIP:
Exit Function
Err_BitMasktoIP:
MsgBox Err.Description
Resume Exit_BitMasktoIP
End Function
Edited to remove leftover debugging code (it's been working for me so long, that I had entirely forgotten about it).
As an aside, it is faster to perform mathematical operations on a computer than it is to work with a string.
This was my "cheating" way:
Option Explicit
Public Function ConvertMaskToCIDR(varMask As Variant) As String
Dim strCIDR As String
Dim mask As String
mask = CStr(varMask)
Select Case mask
Case "255.255.255.255":
strCIDR = "/32"
Case "255.255.255.254":
strCIDR = "/31"
Case "255.255.255.252":
strCIDR = "/30"
Case "255.255.255.248":
strCIDR = "/29"
Case "255.255.255.240":
strCIDR = "/28"
Case "255.255.255.224":
strCIDR = "/27"
Case "255.255.255.192":
strCIDR = "/26"
Case "255.255.255.128":
strCIDR = "/25"
Case "255.255.255.0":
strCIDR = "/24"
Case "255.255.254.0":
strCIDR = "/23"
Case "255.255.252.0":
strCIDR = "/22"
Case "255.255.248.0":
strCIDR = "/21"
Case "255.255.240.0":
strCIDR = "/20"
Case "255.255.224.0":
strCIDR = "/19"
Case "255.255.192.0":
strCIDR = "/18"
Case "255.255.128.0":
strCIDR = "/17"
Case "255.255.0.0":
strCIDR = "/16"
Case "255.254.0.0":
strCIDR = "/15"
Case "255.252.0.0":
strCIDR = "/14"
Case "255.248.0.0":
strCIDR = "/13"
Case "255.240.0.0":
strCIDR = "/12"
Case "255.224.0.0":
strCIDR = "/11"
Case "255.192.0.0":
strCIDR = "/10"
Case "255.128.0.0":
strCIDR = "/9"
Case "255.0.0.0":
strCIDR = "/8"
Case "254.0.0.0":
strCIDR = "/7"
Case "252.0.0.0":
strCIDR = "/6"
Case "248.0.0.0":
strCIDR = "/5"
Case "240.0.0.0":
strCIDR = "/4"
Case "224.0.0.0":
strCIDR = "/3"
Case "192.0.0.0":
strCIDR = "/2"
Case "128.0.0.0":
strCIDR = "/1"
Case "0.0.0.0":
strCIDR = "/0"
End Select
ConvertMaskToCIDR = strCIDR
End Function
Public Function NumUsableIPs(cidr As String) As Long
Dim strHosts As String
If Len(cidr) > 3 Then
'They probably passed a whole address.
Dim slashIndex As String
slashIndex = InStr(cidr, "/")
If slashIndex = 0 Then
NumUsableIPs = 1
Exit Function
End If
cidr = Right(cidr, Len(cidr) - slashIndex + 1)
End If
Select Case cidr
Case "/32":
strHosts = 1
Case "/31":
strHosts = 0
Case "/30":
strHosts = 2
Case "/29":
strHosts = 6
Case "/28":
strHosts = 14
Case "/27":
strHosts = 30
Case "/26":
strHosts = 62
Case "/25":
strHosts = 126
Case "/24":
strHosts = 254
Case "/23":
strHosts = 508
Case "/22":
strHosts = 1016
Case "/21":
strHosts = 2032
Case "/20":
strHosts = 4064
Case "/19":
strHosts = 8128
Case "/18":
strHosts = 16256
Case "/17":
strHosts = 32512
Case "/16":
strHosts = 65024
Case "/15":
strHosts = 130048
Case "/14":
strHosts = 195072
Case "/13":
strHosts = 260096
Case "/12":
strHosts = 325120
Case "/11":
strHosts = 390144
Case "/10":
strHosts = 455168
Case "/9":
strHosts = 520192
Case "/8":
strHosts = 585216
Case "/7":
strHosts = 650240
Case "/6":
strHosts = 715264
Case "/5":
strHosts = 780288
Case "/4":
strHosts = 845312
Case "/3":
strHosts = 910336
Case "/2":
strHosts = 975360
Case "/1":
strHosts = 1040384
End Select
NumUsableIPs = strHosts
End Function