собственно вопрос в названии темы. |
|
hk1209 Пользователь Сообщений: 271 |
#2 18.09.2014 16:26:37 можно создать формулу, затем проверить, содержит ли, например, A2, число или текст, =HaveNumbers(A2)
|
||
IsNumeric — точно. |
|
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
Только учтите, что вместе с IsNumeric лучше так же использовать Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Kuzmich Пользователь Сообщений: 7998 |
Надо еще учесть, что даты тоже числа. |
Слава богу, в моем случае этого учитывать не нужно. Извините за ОФФ. я конечно давно зарегистрировался, уже не вспомнить, но… Регистрация: 1 Янв 1970, — я ж тогда ещё и не родился. |
|
Dolphin Пользователь Сообщений: 2737 |
#8 18.09.2014 17:16:19
Изменено: Dolphin — 18.09.2014 17:19:59 There is no knowledge that is not power |
||
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#9 18.09.2014 17:40:34
Если формат ячейки установлен для Дат — то IsNumeric не будет считать дату числом. Это актуально только если формат ячеек общий. Но в этом случае все будет правильно — ведь дата тогда и отображаться будет как число… Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
есть ещё одна ошибка с объединенными ячейками |
|
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
Очень описательно. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
Николай Юманов Пользователь Сообщений: 70 |
#12 19.09.2014 14:25:47
Точно! Дело было не в бабине… значение переменной iKol я задал через Inputbox вроде цифры, но в кавычках. <#0> |
||
Сливочный Пользователь Сообщений: 178 Win 10, MSO 2016 |
Здравствуйте! Перед занесением диапазона в массив воткнул проверку всех значений диапазона через цикл FOR-NEXT, на отсутствие отрицательных чисел и не чисел, дак вот почему-то при проверке на не числа редактор выделяет isnumeric и останавливается. |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#14 01.08.2016 12:26:08
А путь тут причём? )) Покажите код, лучше вместе с небольшим файлом-примером. |
||
Сливочный Пользователь Сообщений: 178 Win 10, MSO 2016 |
Юрий М, прошу прощения, забыл прикрепить файл. Макрос в котором ошибка — myarray а нет не забыл оказывается, что не так? файл-пример уменьшить? Изменено: Сливочный — 01.08.2016 12:33:07 |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
А зачем там Is Nothing? Удалите это. |
Сливочный Пользователь Сообщений: 178 Win 10, MSO 2016 |
Юрий М, надо проверить, если проверяемое значение не число или число но меньше 0, выйти из макроса. |
Юрий М Модератор Сообщений: 60570 Контакты см. в профиле |
#18 01.08.2016 12:46:06 Я же говорил — Nothig уберите:
|
||
Сливочный Пользователь Сообщений: 178 Win 10, MSO 2016 |
#19 01.08.2016 12:55:53 Юрий М, всё работает, спасибо! |
You can use the IsNumeric function in VBA to check if a given cell is a number.
This function will return True if the value in a given cell is recognized as a number.
Otherwise, the function will return False.
Here is one common way to use this function in practice:
Sub CheckNumeric()
Dim i As Integer
For i = 1 To 9
If IsNumeric(Range("A" & i)) = True Then
Range("B" & i) = "Numeric Value"
Else
Range("B" & i) = "Not a Numeric Value"
End If
Next i
End Sub
This particular macro will check if each cell in the range A1:A9 is a number.
If a cell is a number, then “Numeric Value” will be returned in the corresponding cell in the range B1:B9.
If a cell is not a number, then “Not a Numeric Value” will be returned instead.
The following example shows how to use this syntax in practice.
Example: How to Use IsNumeric in VBA
Suppose we have the following column of values in Excel:
Suppose we would like to check if each cell in column A is number.
We can create the following macro to do so:
Sub CheckNumeric()
Dim i As Integer
For i = 1 To 9
If IsNumeric(Range("A" & i)) = True Then
Range("B" & i) = "Numeric Value"
Else
Range("B" & i) = "Not a Numeric Value"
End If
Next i
End Sub
When we run this macro, we receive the following output:
Column B displays output that tells us whether or not each corresponding cell in column A is recognized as a number or not.
Here are some interesting things to note from the output:
- Numbers with decimals are recognized as numbers.
- Percentages are recognized as numbers.
- Dates are not recognized as numbers.
- Text with numbers are not recognized as numbers.
Note: You can find the complete documentation for the VBA IsNumeric function here.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
How to Convert String to Integer in VBA
How to Convert String to Double in VBA
How to Check if String Contains Another String in VBA
Return to VBA Code Examples
This tutorial will teach you how to use the IsNumeric and IsNumber functions in VBA to check if values are numbers.
IsNumeric is a built-in VBA function, while IsNumber is an Excel function which can be called from VBA code.
Difference between IsNumber and IsNumeric in VBA
IsNumber checks if a value is stored as a number. Whereas, IsNumeric checks if a value can be converted into a number.
For example, if you pass a blank cell as a parameter, IsNumber will return FALSE, while IsNumeric will return TRUE. Also, if you pass a cell containing number stored as a text, IsNumber will return FALSE and IsNumeric TRUE.
You need to pay attention to these limitations of both functions and decide in which cases is better to use IsNumeric and when IsNumber.
Using IsNumeric in VBA
IsNumeric is the VBA function which checks if a value is numeric and returns a Boolean TRUE or FALSE as a result.
The function can take a variable or a cell value.
Here is an example of taking a cell value:
If IsNumeric(Sheet1.Range("A1").Value) = True Then
MsgBox "The value in A1 is numeric"
Else
MsgBox "The value in A1 is not numeric"
End If
In this example, we check if the value from the cell A1 is numeric using the IsNumeric. This function returns the appropriate message, depending on the result of the function.
This next example perform the same operation, except with a variable instead of a cell value:
Dim n as Variant
n = Sheet1.Range("A1").Value
If IsNumeric(n) = True Then
MsgBox "The value in A1 is numeric"
Else
MsgBox "The value in A1 is not numeric"
End If
Using IsNumber in VBA
IsNumber is an Excel Function, which can be used in VBA. It has an almost similar output as IsNumeric. Let’s look at the example of the IsNumber function:
If Application.WorksheetFunction.IsNumber(Sheet1.Range("A1").Value) = True Then
MsgBox "The value in A1 is numeric"
Else
MsgBox "The value in A1 is not numeric"
End If
As you can see from the code, the difference is in the syntax when calling the function. Since IsNumber is the Excel function, we need to put Application.WorksheetFunction before the function call.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.
Проверка переменных и выражений
Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.
Синтаксис функций для проверки переменных и выражений:
Expression — выражение, переменная или необязательный аргумент для IsMissing.
Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.
Функция IsArray
Описание функции
Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:
- True — переменная является массивом;
- False — переменная не является массивом.
Пример с IsArray
Sub Primer1() Dim arr1(), arr2(1 To 10), arr3 Debug.Print IsArray(arr1) ‘Результат: True Debug.Print IsArray(arr2) ‘Результат: True Debug.Print IsArray(arr3) ‘Результат: False arr3 = Array(1, 2, 3, 4, 5) Debug.Print IsArray(arr3) ‘Результат: True End Sub |
Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.
Функция IsDate
Описание функции
Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:
- True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
- False — в иных случаях.
Пример с IsDate
Sub Primer2() Dim d1 As String, d2 As Date Debug.Print IsDate(d1) ‘Результат: False Debug.Print IsDate(d2) ‘Результат: True d1 = «14.01.2023» Debug.Print IsDate(d1) ‘Результат: True Debug.Print IsDate(Now) ‘Результат: True End Sub |
Функция IsEmpty
Описание функции
Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:
- True — переменная содержит значение Empty;
- False — переменной присвоено значение, отличное от Empty.
Пример с IsEmpty
Sub Primer3() Dim s As String, v As Variant Debug.Print IsEmpty(s) ‘Результат: False Debug.Print IsEmpty(v) ‘Результат: True v = 125 Debug.Print IsEmpty(v) ‘Результат: False Range(«A1»).Clear Debug.Print IsEmpty(Range(«A1»)) ‘Результат: True Range(«A1») = 123 Debug.Print IsEmpty(Range(«A1»)) ‘Результат: False End Sub |
Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).
Функция IsError
Описание функции
Функция IsError возвращает логическое значение, указывающее, является ли аргумент функции значением ошибки, определенной пользователем:
- True — аргумент функции является значением ошибки, определенной пользователем;
- False — в иных случаях.
Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.
Пример с IsError
Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:
Function Vkuba(x) If IsNumeric(x) Then Vkuba = x ^ 3 Else Vkuba = CVErr(25) End If End Function Sub Primer4() Debug.Print Vkuba(5) ‘Результат: 125 Debug.Print IsError(Vkuba(5)) ‘Результат: False Debug.Print Vkuba(«пять») ‘Результат: Error 25 Debug.Print IsError(Vkuba(«пять»)) ‘Результат: True End Sub |
Функция IsMissing
Описание функции
Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:
- True — если в процедуру не было передано значение для необязательного аргумента;
- False — значение для необязательного аргумента было передано в процедуру.
Пример с IsMissing
Function Scepka(x, Optional y) If Not IsMissing(y) Then Scepka = x & y Else Scepka = x & » (а необязательный аргумент не подставлен)» End If End Function Sub Primer5() Debug.Print Scepka(«Тропинка», » в лесу») ‘Результат: Тропинка в лесу Debug.Print Scepka(«Тропинка») ‘Результат: Тропинка (а необязательный аргумент не подставлен) End Sub |
Функция IsNull
Описание функции
Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:
- True — значением переменной или выражения является Null;
- False — в иных случаях.
Пример с IsNull
Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:
Sub Primer6() Dim Var Var = Null If Var = Null Then Debug.Print Var ‘Результат: «» If Var <> Null Then Debug.Print Var ‘Результат: «» If IsNull(Var) Then Debug.Print Var ‘Результат: Null End Sub |
Функция IsNumeric
Описание функции
Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:
- True — если аргумент функции может рассматриваться как число;
- False — в иных случаях.
Пример с IsNumeric
Sub Primer7() Debug.Print IsNumeric(«3,14») ‘Результат: True Debug.Print IsNumeric(«четыре») ‘Результат: False End Sub |
Функция IsObject
Описание функции
Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:
- True — переменная содержит ссылку на объект или значение Nothing;
- False — в иных случаях.
Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.
Пример с IsObject
Sub Primer8() Dim myObj As Object, myVar As Variant Debug.Print IsObject(myObj) ‘Результат: True Debug.Print IsObject(myVar) ‘Результат: False Set myVar = ActiveSheet Debug.Print IsObject(myVar) ‘Результат: True End Sub |
In VBA, to test whether an expression is a number, the IsNumeric
function can be used.
Description
The IsNumeric function evaluates whether the input expression is a number and returns a Boolean value (TRUE or FALSE). It returns True if the entire expression is a number; otherwise, it returns False.
Syntax
IsNumeric(expression)
The input expression is either a numeric expression or a string expression.
VBA examples of IsNumeric
Example 1 – Using IsNumeric with IF-THEN-ELSE
The following VBA function CheckNumeic uses IsNumeric to test whether input1 is numeric or not with an IF-THEN-ELSE statement.
Function CheckNumeric(ByVal input1) As String If IsNumeric(input1) = True Then MyFunction1 = "Input is numeric" Else MyFunction1 = "Input is not numeric" End If End Function
I would want to draw your attention to line 2. While this line is correct, it is not necessary. Instead, it can be written as:
If IsNumeric(input1) Then
In VBA, whenever you perform a logical test, for the condition of TRUE, you don’t have to type the =TRUE
in the statement.
Example2 – Negate the result of IsNumeric
The VBA function below returns the opposite of IsNumeric
. The function uses the same IF-THEN-ELSE structure.
Function IsNumericReverse(ByVal input1) As Boolean If IsNumeric(input1) = True Then IsNumericReverse = False Else IsNumericReverse = True End If End Function
However, this entire structure is not necessary. Instead, the function can be simplified as follows. The Not logical operator can be used to reverse (negate) the answer of IsNumeric, which serves the objective of the function in this case.
Function IsNumericReverse(ByVal input1) As Boolean IsNumericReverse = Not (IsNumeric(input1)) End Function
Example 3 – VBA action if not numeric
The VBA function counts the number of non-numeric cells in the input range. In line 5, note the use of Not
with IsNumeric
. In the sentence structure here, putting a space after No
t is enough, which is equivalent to using a bracket after Not
to wrap the condition being tested.
Function countNonNumeric(range1 As Range) As Long Dim cell As Range Dim counter As Long For Each cell In range1.Cells If Not IsNumeric(cell.Value) Then 'use Not to test for non-numeric counter = counter + 1 End If Next countNonNumeric = counter End Function
Special Case with Blank
When using IsNumeric, you need to be aware that “blank” (string of zero length) does not mean zero (0) and it is considered to be non-numeric:
IsNumeric("")
returns False
Therefore, when you write your macro, if you want to treat blank as numeric, you may have to use conditional statements to handle the case of blank string inputs.
Special Case with Dates
Another special case with IsNumeric
is the treatment of date inputs. Most people conceptually think dates are numeric (after all, they can be converted into date-serials in the computer). However the IsNumeric
function in VBA considers dates as non-Numeric:
IsNumeric("10/2/2020")
returns False
Even if you try to input a date truly in Date format, IsNumeric still returns False:
IsNumeric(DateSerial(2020, 10, 2))
returns False
Therefore, you may also need to use conditional statements to handle the case of dates expressions.
Special Case with Time
Handling of time expressions by the ISNUMERIC is difficult to manage, or I would describe it as unpredictable. Therefore, when you input expressions contain time expressions, you must test your macro thoroughly.
There are three possibilities with time expressions. Let’s experiment with the macro below. In cell A1, we place a time of “3:00:00 AM” first. Then we run the macro which test 3 cases:
- time in form of string (variable x1)
- time in form of time value (variable x2)
- time placed in a cell in an Excel sheet (variable x3)
Sub TimeCases() Dim y x1 = IsNumeric("3:00:00 AM") x2 = IsNumeric(TimeSerial(3, 0, 0)) y = Range("A1").Value x3 = IsNumeric(y) MsgBox x1 &amp;amp;amp;amp; Chr(10) &amp;amp;amp;amp; x2 &amp;amp;amp;amp; Chr(10) &amp;amp;amp;amp; x3 End Sub
Run the macro and the answers will be displayed in the Msgbox:
Calling Excel Worksheet Function ISNUMBER() in VBA
As an alternative to IsNumeric
in VBA, you may call the Excel worksheet function ISNUMBER()
in your macro. There are two ways to do this. See line 2 and line 3 in the VBA function below, which do the same job. (I personally prefer Method 2.)
Function CallIsNumber(input1) As Boolean x = WorksheetFunction.IsNumber(input1) 'Method 1' x = Application.IsNumber(input1) 'Method 2' CallIsNumber = x End Function
VBA ISNUMERIC vs ISNUMBER Worksheet Function
Although you can either use IsNumeric
or Excel worksheet function ISNUMBER
to check whether an input expression is numeric, you have to be aware of the differences between the two methods in order to program your macros correctly to produce expected result.
Expression | Date type of expression | ISNUMERIC returns (VBA) | ISNUMBER returns (worksheet function) |
123 | Number | TRUE | TRUE |
“123” | Number in form of string | TRUE | FALSE |
12/2/2020 | Date | FALSE | TRUE |
“12/2/2020” | Date in form of String | FALSE | FALSE |
DateSerial(2020,10,2) | Date in form of Date Value | FALSE | FALSE |
3:00:00 AM | Time placed in a cell | TRUE | TRUE |
“3:00:00 AM” | Time in form of String | FALSE | FALSE |
TimeSerial(3, 0,0) | Time in form of Time Value | FALSE | FALSE |
“” (blank) | String | FALSE | TRUE |
See also:
- Else if in VBA