I have an integer I'd like to test to see if it is a repeating number, ie
999
9999
99999
the input value range for what the integer is being used for is any three to five digit number, and sometimes that number may be all 9's. Outside of just using multiple OR statements, I'm wondering if there is a more "elegant" way to test this?
Something like this =(LEN(SUBSTITUTE(A1,MID(A1,1,1),""))=0)
Here is a short little example to help you get started. This vba code checks to see if it is one of your repeating numbers (999,9999,99999) and makes a message box if it is or not one of your repeating numbers.
Sub Test()
Dim MyVal As Long
MyVal = Range("A1").Value
If MyVal = 999 Or MyVal = 9999 Or MyVal = 99999 Then
MsgBox "Integer is a repeating number."
Else
MsgBox "Integer is not a repeating number."
End If
End Sub
Related
I have a row with values something like this, How to extract first two digits that come after the text 'ABCD' to another cell, any formula or vba? There may be a few chars in between or sometimes none.
ABCD 10 sadkf sdfas
ABCD-20sdf asdf
ABCD 40
ABCD50 asdf
You can do this with a worksheet formula. No need for VBA.
Assuming you do not need to test for the presence of two digits:
=MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2)
If you need to test for the presence of two digits, you can try:
=IF(ISNUMBER(-RIGHT(MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2),1)),MID(A1,MIN(FIND({1,2,3,4,5,6,7,8,9,0},A1&"1234567890")),2),"Invalid")
In general, it is always a good idea to show some code in StackOverflow. Thus, you show that you have tried something and you give some directions for the answer.
Concerning the first two digits extract, there are many ways to do this. Starting from RegEx and finishing with a simple looping of the chars and checking each one of them.
This is the loop option:
Public Function ExtractTwoDigits(inputString As String) As Long
Application.Volatile
Dim cnt As Long
Dim curChar As String
For cnt = 1 To Len(inputString)
curChar = Mid(inputString, cnt, 1)
If IsNumeric(curChar) Then
If Len(ExtractTwoDigits) Then
ExtractTwoDigits = ExtractTwoDigits & curChar
Exit Function
Else
ExtractTwoDigits = curChar
End If
End If
Next cnt
ExtractTwoDigits = -1
End Function
Application.Volatile makes sure that the formula recalculates every time;
-1 is the answer if no two digits exist in the inputString;
IsNumeric checks whether the string inside is numeric;
As a further step, you may try to make the function a bit robust, extracting the first 1, 3, 4 or 5 digits, depending on a parameter that you put. Something like this =ExtractTwoDigits("tarato123ra2",4), returning 1232.
RegEx Version:
Public Function GetFirstTwoNumbers(ByVal strInput As String) As Integer
Dim reg As New RegExp, matches As MatchCollection
With reg
.Global = True
.Pattern = "(\d{2})"
End With
Set matches = reg.Execute(strInput)
If matches.Count > 0 Then
GetFirstTwoNumbers = matches(0)
Else
GetFirstTwoNumbers = -1
End If
End Function
You have to enable Microsoft Regular Expressions 5.5 under extras->references. The pattern (\d{2}) matches 2 digits, return value is the number, if not existing -1.
Note: it only extracts 2 successive numbers.
If you place this function into a module, you can use it like normal formula.
Here a great site to to get into regEx.
I have a string called Policynumber
I need to know if it begins with a 1 or a 2 so I can create an if statement for if it starts with 1 do something and if it starts with 2 to do something else.
I keep finding ways to do this for string text but not for a variable.
I have tried doing the following:
If policynumber Like "1*" Then
display.text = policynumber
End If
I am simply looking for possible ways to know what the first character is and therefore determine if it's a 1 or a 2. When I try using the variable name or even a textbox.text I get no result in the display textbox so I know it's not working.
I would use VBA's ASC() function for this purpose. This function returns the ASCII code of the first character of a string. ASCII for the character 1 is 49 and 2 is 50. Therefore ...
Dim PolicyNumber As String
Dim n As Integer
PolicNumber = "1ABC-45678910"
n = ASC(PolicyNumber)
MsgBox "Policy number starts with a " & Chr(n)
For testing the result you can use either If n = 49 Then or If Chr(n) = "1" Then.
I am trying to create a macro for Word 2013 that does the following: the macro should capture the value of a cell of a word table and then add another value and paste the result in another cell of the same table.
My code so far is:
Sub prueba()
Dim a As String, b As String, c As String
Dim entero1 As Double, entero2 As Double
Dim resultado As Double
Dim tabla1 As Table
Set tabla1 = ActiveDocument.Tables(1)
a = tabla1.Cell(Row:=1, Column:=3).Range
entero1 = CDbl(a)
End Sub
But when I run it I get an error 13
To evaluate the error add the following two lines to validate if the data type obtained in "a" was a string
MsgBox (TypeName(a))
MsgBox (a)
And I got the following
I believe that the CDbl function does not finish converting the string to double because as they see the chain has a small square, what is not like to erase it so that the conversion is achieved.
Thank you very much for your help.
One way of extracting just the numeric portion of the Range would be to use the Val function, e.g.
entero1 = Val(a)
If the string a contained, for instance, 123.23XYZ4567 then Val(a) would return the number 123.23.
That should ensure that the non-numeric character that you are getting at the end of your Range is removed.
The answer provided by YowE3K is elegant and has my vote. For further information:
That 'small square' is the end of cell marker which is part of Cell.Range.Text (.Text is the default property returned when returning a range object is inappropriate).
To actually remove the end of cell marker (Chr(13) & Chr(7)) you can use something like this:
?CDbl(Replace$(Selection.Range.Cells(1).Range.Text, Chr(13) & Chr(7), vbNullString))
A possible advantage of this approach is that it may provide better opportunity to trap errors if you are only expecting numeric characters.
I am creating a probability macro where user enters number of players in a card game. If I enter string (ex, Joe), non-integer(ex, 15.67), or integer less than 0 (ex, -25), the InputBox should loop. However, integers greater than 0 should terminate the loop. (I have to force kill Excel to stop the InputBox regardless of user input.)
I want the InputBox to close / Exit Sub once an integer greater than 0 is entered. What am I doing wrong here?
Sub GenerateCards()
Players = InputBox("How many players? Please enter an integer.")
Do Until TypeName(Players) = "Integer" And Players > 0 ' why does this loop even if both conditions are met (ex, Players=5?)
Players = InputBox("How many players? Please enter an integer.")
Loop
End Sub
InputBox() always returns a string, so TypeName() will always return "String".
But you can test if the string that's returned is an integer. First, you can use IsNumeric() to test if the string is a numeric value. Then, you can safely cast it to a Double or an Integer. In fact, you can cast it to both and then compare them against each other. If they're the same, you've got an integer value. For example:
Sub GenerateCards()
Do
Players = InputBox("How many players? Please enter an integer.")
If IsNumeric(Players) Then
If CDbl(Players) = CLng(Players) And Players > 0 Then
' Integer > 0 entered. Exit loop...
Exit Do
End If
End If
Loop
End Sub
I have this code, which sorts an input number into a convenient range:
Public Sub TestCase2()
Dim Number As Long
Dim Message As String
Number = InputBox("Enter a number:", "Number entry")
Message = "Number is "
Select Case Number
Case Is < -10
MsgBox (Message & "less than -10")
Case Is < 0
MsgBox (Message & "equal to or greater than -10 but less than zero")
Case Is = 0
MsgBox (Message & "equal to zero")
Case Is < 10
MsgBox (Message & "greater than zero but less than 10")
Case Else
MsgBox (Message & "greater than or equal to 10")
End Select
End Sub
It falls over when I enter -10.5 - I would have thought it would output:
Number is less than -10
But it says:
Number is equal to or greater than -10 but less than zero.
If I enter -10.6, the output is as expected: Number is less than -10.
Also, it falls over with an entry of 0.001: it says Number is equal to zero. Which it isn't.
I cannot work with integers here - the input has to have decimals (up to 3).
Is there a neater way of doing this? Many thanks for your constructive input.
Regards,
Shane (VBA newbie of 4 weeks).
PS I know I can do this with If-Then statements, but I'm just getting to grips with Select Case-Case Else).
InpuBox function returns string. So, to be able to compare value returned by this function, you need to convert it into proper numeric format:
Dim sNumber As String
sNumber = InputBox(...)
'prevent Cancel click
If sNmber = "" Then Exit Sub
'prevent non-numeric value
If Not IsNumeric(sNmber) Then Exit Sub
Select Case CDbl(sNumber)
....
If you want to use If .. else statement instead of Select case , please see: If .. Then ... Else ...
Number may have to be dimmed as Single or Double
Dim Number As Single