ironegg 1904 / 781 / 31 Регистрация: 11.02.2010 Сообщений: 1,567 |
||||||||
1 |
||||||||
Как быстро определить: целое ли число?04.04.2010, 14:09. Показов 29948. Ответов 7 Метки нет (Все метки)
сейчас проверка отсутствия дробной части сделана так.
.
0 |
1605 / 1337 / 291 Регистрация: 25.10.2009 Сообщений: 3,487 Записей в блоге: 2 |
|
04.04.2010, 14:17 |
2 |
Сообщение было отмечено как решение РешениеМожет использовать Fix ? Типо если x<>fix(x) тогда есть дробная часть
3 |
1904 / 781 / 31 Регистрация: 11.02.2010 Сообщений: 1,567 |
|
04.04.2010, 14:33 [ТС] |
3 |
а если число отрицательное?. в упрощенном примере который я привел выше, этого нет, но вообще мне надо чтобы он и отрицательные корректно обрабатывал.
0 |
1605 / 1337 / 291 Регистрация: 25.10.2009 Сообщений: 3,487 Записей в блоге: 2 |
|
04.04.2010, 14:38 |
4 |
Ну и отрицательное можно. Fix() возвращает только целую часть.К примеру x=5.6 ,Fix(x)=5 . И если X<>Fix(X) тогда дробная часть есть,а если равны-нету
1 |
1904 / 781 / 31 Регистрация: 11.02.2010 Сообщений: 1,567 |
|
04.04.2010, 14:52 [ТС] |
5 |
Fix() возвращает только целую часть точно. надо больше спать. в данном случае одинаково в какую сторону округлять.
0 |
1605 / 1337 / 291 Регистрация: 25.10.2009 Сообщений: 3,487 Записей в блоге: 2 |
|
04.04.2010, 15:01 |
6 |
Ну а Вы вообще Mod хотели =) он медленный и не работает с большими числами. Наверное,Ваша конструкция самая быстрая (x-CInt(x)) . А кстати попробуйте If x<>Round(x) . Это округление…хотя наврятли оно будет работать достаточно быстро
1 |
аналитика здесь больше нет… 3372 / 1670 / 184 Регистрация: 03.02.2010 Сообщений: 1,219 |
||||||||||||
04.04.2010, 15:37 |
7 |
|||||||||||
Сообщение было отмечено как решение Решениесамый быстрый
4 |
1904 / 781 / 31 Регистрация: 11.02.2010 Сообщений: 1,567 |
|
04.04.2010, 22:29 [ТС] |
8 |
i = 129 действительно дает прирост20%. но по известным причинам не подходит .
0 |
Содержание
- Метод WorksheetFunction.IsNumber (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Примечания
- Поддержка и обратная связь
- Метод WorksheetFunction.IsNumber (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Примечания
- Поддержка и обратная связь
- IsNumeric VBA Function Checks if Cell is a Number
- The VBA Tutorials Blog
- Introduction to IsNumeric
- IsNumeric Examples
- Check if a Cell is a Number
- Check if All Cells in a Range are Numeric
- IsNumeric vs ISNUMBER
- Final Thoughts
- Функция IsNumeric
- Примеры запросов
- Пример VBA
- Using Isnumeric and Isnumber in VBA
- Difference between IsNumber and IsNumeric in VBA
- Using IsNumeric in VBA
- Using IsNumber in VBA
- VBA Coding Made Easy
- VBA Code Examples Add-in
Метод WorksheetFunction.IsNumber (Excel)
Проверяет тип значения и возвращает значение True или False в зависимости от того, ссылается ли значение на число.
Синтаксис
expression. IsNumber (Arg1)
Выражение Переменная, представляющая объект WorksheetFunction .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Arg1 | Обязательный | Variant | Value — значение, которое требуется протестировать. Значение может быть пустым (пустая ячейка), ошибкой, логическим, текстовым, числом или ссылочным значением или именем, ссылающимся на любое из этих значений, которое требуется проверить. |
Возвращаемое значение
Boolean
Примечания
Аргументы значений функций IS не преобразуются. Например, в большинстве других функций, где требуется число, текстовое значение 19 преобразуется в число 19. Однако в формуле ISNUMBER(«19») значение 19 не преобразуется из текстового значения, и функция IsNumber возвращает значение False.
Функции IS полезны в формулах для проверки результата вычисления. В сочетании с функцией IF они предоставляют метод для обнаружения ошибок в формулах.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Метод WorksheetFunction.IsNumber (Excel)
Проверяет тип значения и возвращает значение True или False в зависимости от того, ссылается ли значение на число.
Синтаксис
expression. IsNumber (Arg1)
Выражение Переменная, представляющая объект WorksheetFunction .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Arg1 | Обязательный | Variant | Value — значение, которое требуется протестировать. Значение может быть пустым (пустая ячейка), ошибкой, логическим, текстовым, числом или ссылочным значением или именем, ссылающимся на любое из этих значений, которое требуется проверить. |
Возвращаемое значение
Boolean
Примечания
Аргументы значений функций IS не преобразуются. Например, в большинстве других функций, где требуется число, текстовое значение 19 преобразуется в число 19. Однако в формуле ISNUMBER(«19») значение 19 не преобразуется из текстового значения, и функция IsNumber возвращает значение False.
Функции IS полезны в формулах для проверки результата вычисления. В сочетании с функцией IF они предоставляют метод для обнаружения ошибок в формулах.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
IsNumeric VBA Function Checks if Cell is a Number
The VBA Tutorials Blog
Introduction to IsNumeric
The IsNumeric VBA function checks if a cell is a number and expresses the answer as a Logical Boolean ( True or False ). The IsNumeric VBA function is a counterpart to the Excel ISNUMBER function, but the expressions don’t always produce the same results.
This isn’t the first time you’ve seen me use IsNumeric in my VBA macros, but in this tutorial I’ll explain how it’s used and what it’s good for. Let’s get started.
- If IsNumeric thinks your expression is a number, it will return a value of True.
- If it’s not a number, it will return False.
The syntax for the IsNumeric function can’t get any simpler:
As you can see, IsNumeric accepts one argument: an expression of the Variant Data Type. I know, I know. The complicated jargon isn’t necessary.
All you need to know is that IsNumeric can pretty much evaluate anything. A cell, a string, a date, a range. It won’t choke up on any of these, but that doesn’t mean it’ll give you the answer you want.
For example, if you enter a range, like Range(«A1:B5») , into an IsNumeric expression, it will always return False even if all the values in the range ARE numeric. The IsNumeric function won’t loop through each cell in your range and check whether each of them are numeric. You’ll have to do that with a loop of your own, like a For Each loop. I’ll show you a macro that does that in the IsNumeric Examples section.
Because IsNumeric returns True or False, it’s a great expression to include inside If Statements. Let’s take a look at a couple examples.
IsNumeric Examples
Check if a Cell is a Number
Make powerful macros with our free VBA Developer Kit
It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.
This example macro tests if the value in cell A1 is a number. If it is, the value in cell B1 says it’s a number. Otherwise, it says it’s not a number.
You don’t need to put the = True in the above If Statement, but I included it to make the macro easier to read.
If you have a macro that performs arithmetic expressions, it’s a good practice to use IsNumeric to make sure your input is numeric before performing the math. As a side note, it’s also a good to make sure your input isn’t empty by using the IsEmpty function. That’s another tutorial for another day.
Check if All Cells in a Range are Numeric
The above macro checks each cell in your range and the moment it finds one that isn’t numeric, it exits the For Each loop and lets you know there are non-numeric cells in the range.
As a programmer, you can perform different actions based on whether the entire range is numeric or not. Checks like this one give you more control over how you handle errors.
IsNumeric vs ISNUMBER
To test how the IsNumeric VBA and the ISNUMBER Excel functions behave, we’re going to make a User Defined Function (UDF) to evaluate the following cells in Column A:
We’ll use the native ISNUMBER function of Excel in Column C and we’ll use the the following UDF to represent our VBA IsNumeric function in Column B.
We’ll evalulate the expressions in Column A using both the VBA IsNumeric() function (Column B) and the Excel =ISNUMBER() function (Column C). You would expect them to be identical, right? You’re about to be surprised…
The two functions yield completely different answers when evaluating the same data. IT’S CRAZY!
By looking at the comparison image, you can see the VBA IsNumeric function considers empty cells numeric, but the Excel ISNUMBER function does not. That’s why I said earlier that it’s a good VBA practice to check if your cell is empty by using the IsEmpty function when you use the IsNumeric function.
Another difference you can see is in how the two functions treat dates and times. IsNumeric VBA says times are numbers, but dates are not. It also says the combination of dates and times are not numeric. ISNUMBER, on the other hand, says all 3 date/time cells are numeric.
Final Thoughts
Congratulations! You’re now an IsNumeric expert! You certainly know more about IsNumeric than the average Excel user, and for that you should be excited.
IsNumeric is a great VBA function, but, as you’ve seen, you have to be careful when using it if there’s a chance your input may be blank or if you’re evaluating dates and times.
It’s important to know what a function does well, but it’s equally important to know what a function doesn’t do well. I hope you find this VBA tutorial informative and you’re IsNumeric in your own macros!
For more VBA tips, techniques, and tactics, subscribe to our VBA Insiders email series using the form below. After you subscribe, share what you’re automating on Twitter and Facebook.
Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.
Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.
Источник
Функция IsNumeric
Возвращает boolean value, указывающее, выражение можно высмеять как число.
Обязательный аргумент выражениеаргумент является значением типа Variant, содержащим числовое выражение или строковое выражение.
IsNumeric возвращает true, если выражение целиком распознается как число; в противном случае возвращается false.
IsNumeric возвращает false, если выражение является выражение даты.
Примеры запросов
SELECT IsNumeric([UnitPrice]) AS Expr1 FROM ProductSales;
Функция оценивает, является ли значение «UnitPrice» допустимым числом, и возвращает результат «-1» для значения «Истина» и «0» для значения «Ложь» в столбце «Вырасть1». Результат — -1 (Истина).
SELECT IsNumeric([DateofSale]) AS ValidNumber, IsNumeric(«487.34») AS NumberTest FROM ProductSales;
Функция оценивает, является ли «DateofSale» и «487,34» допустимым числом, и возвращает результат «-1» для «Истина» и «0» для ложь в столбцах ValidNumber и NumberTest соответственно. Результат составляет 0 (Ложь) для validNumber и -1(True) для NumberTest.
Пример VBA
Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.
В этом примере функция IsNumeric используется для определения того, может ли переменная быть оценена как число.
Источник
Using Isnumeric and Isnumber in VBA
In this Article
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:
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:
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:
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!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
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
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!