Excel vba if value is a number

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!
vba save as

Learn More!

  • #2

#1
IsNumeric(Cells(1,1))

#2
What do you mean by code? Perhaps
Application.WorkSheetFunction.Code(Range(«A1»))

lenze

Last edited: Jul 22, 2009

  • #3

Hi

1)

Can you be more specific?

Do you mean like the worksheet function IsNumber()?

Questions:
— If the cell has text convertible to a number like the string «123» do you want True or False?
— If the cell has a date, the worksheet function IsNumber() would give you a True. Is this what you want?

2)

I guess you mean the function Asc(). It can also be its big sister AscW() In case of a Unicode character.

  • #4

Thank you for your answers!

pgc01,
— If it’s a date I would like to get FALSE
— If I get a string «123» I would prefer TRUE (but if it’s too complicated, FALSE will do it).

2) by code I mean the worksheet function =Code(), so I’m guessing that your suggestion Asc(Cell(1,1)) will do the job :biggrin:

Thank you guys

  • #5

I have a related question:
1a) I would like to count how many numbers (IsNumeric() will do) different from 0 I have in a given range, say A1:A5.
In the worsheet I would write =SUMPRODUCT(—Isnumber(A1:A5), (A1:A5<>0)).
To find the numbers (even 0), as a first step, I tried

Code:

HowMany = Application.WorksheetFunction.SumProduct(--IsNumeric(rng))

but didn’t work :(

Any suggestions?

Last edited: Jul 22, 2009

  • #6

— If it’s a date I would like to get FALSE
— If I get a string «123» I would prefer TRUE (but if it’s too complicated, FALSE will do it).

Use IsNumeric() as Lenze suggested. It accepts numbers and strings convertible to numbers and refuses dates.
Remark: it also accepts booleans, if you think it’s relevant to your problem test against it.

P. S. Just saw your other post.

Instead of the worksheet function SumProduct() you can use a loop.

Last edited: Jul 22, 2009

  • #7

Thank you!
Managed to create the loop…yay!! (was quite easy though)

Great suggestions guys :biggrin:

ZVI

ZVI

MrExcel MVP


  • #8

Take into account that string «1D2» is recognized as numeric equal to 1*10^2 = 100.
Therefore IsNumeric(«1D2») = True
To avoid it you can use: IsNumeric(Replace(ActiveCell, «D», «?»)

The code below can help you:

Rich (BB code):

<font face=Courier New>
' Count the numerical values in the Rng range
' VBA usage:
'   NumsCount(Range("A1:A5"))       <-- Zeroes are not numerical
'   NumsCount(Range("A1:A5"), True) <-- Zeroes are numerical
' Formula usage: =NumsCount(A1:A5)
Function NumsCount(Rng As Range, Optional UseZero As Boolean) As Long
  Dim arr, v
  arr = Rng
  If Not IsArray(arr) Then ReDim arr(0): arr(0) = Rng
  For Each v In arr
    If IsNum(v) Then
      If UseZero Then
        NumsCount = NumsCount + 1
      ElseIf v <> 0 Then
        NumsCount = NumsCount + 1
      End If
    End If
  Next
End Function

' The same as IsNumeric() but different for strings like "1D2", and skips the boolean values
' If NumOnly=True then strings are not recognised as numeric at all.
' If UseD=True then strings like "1D2" are recognised as numeric.
Function IsNum(TxtOrNum, Optional NumOnly As Boolean, Optional UseD As Boolean) As Boolean
  Select Case VarType(TxtOrNum)
    Case 2 To 6, 14
      ' Any type of numbers
      IsNum = True
    Case 8
      ' vbString
      If Not NumOnly Then
        Dim d As Double
        If Not UseD Then
          If InStr(UCase(TxtOrNum), "D") > 0 Then Exit Function
        End If
        On Error Resume Next
        d = TxtOrNum
        IsNum = Err = 0
      End If
  End Select
End Function</FONT>

Regards,
Vladimir

Last edited: Jul 22, 2009

  • #9

Hi Vladimir

Good idea, your IsNum().

Maybe you want to deal also with another problem. The vba does not care about commas in expressions when it converts to numbers.

For example if in a cell you have «12,3,45» you would say it’s a list, but vba and your IsNum() will say it’s a valid number. Also for «1,23,4.5,67», if you assign it to a double you get 1234.567, the commas don’t matter to vba, but you would not say that’s a number.

In case of a string maybe the best is to use regular expressions and check the possible formats.

ZVI

ZVI

MrExcel MVP


  • #10

Hi Vladimir

Good idea, your IsNum().

Maybe you want to deal also with another problem. The vba does not care about commas in expressions when it converts to numbers.

For example if in a cell you have «12,3,45» you would say it’s a list, but vba and your IsNum() will say it’s a valid number. Also for «1,23,4.5,67», if you assign it to a double you get 1234.567, the commas don’t matter to vba, but you would not say that’s a number.

In case of a string maybe the best is to use regular expressions and check the possible formats.

Hi PGC,

May be additional checking of comma in string is enough for solving the list recognising issue:

Rich (BB code):

<font face=Courier New>
' The same as IsNumeric() but different for strings like "1D2", and skips the boolean values
' If NumOnly=True then strings are not recognised as numeric at all.
' If UseD=True then strings like "1D2" are recognised as numeric.
' Comma in string means the list and recognised as not numerical
Function IsNum(TxtOrNum, Optional NumOnly As Boolean, Optional UseD As Boolean) As Boolean
  Select Case VarType(TxtOrNum)
    Case 2 To 6, 14
      ' Any type of numbers
      IsNum = True
    Case 8
      ' vbString
      If Not NumOnly Then
        If InStr(TxtOrNum, ",") > 0 Then Exit Function ' <- Comma means the list
        Dim d As Double
        If Not UseD Then
          If InStr(UCase(TxtOrNum), "D") > 0 Then Exit Function
        End If
        On Error Resume Next
        d = TxtOrNum
        IsNum = Err = 0
      End If
  End Select
End Function</FONT>

Regards,
Vladimir

Last edited: Jul 22, 2009

Содержание

  1. Метод WorksheetFunction.IsNumber (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Примечания
  6. Поддержка и обратная связь
  7. Using Isnumeric and Isnumber in VBA
  8. Difference between IsNumber and IsNumeric in VBA
  9. Using IsNumeric in VBA
  10. Using IsNumber in VBA
  11. VBA Coding Made Easy
  12. VBA Code Examples Add-in
  13. Функция IsNumeric
  14. Примеры запросов
  15. Пример VBA
  16. WorksheetFunction.IsNumber method (Excel)
  17. Syntax
  18. Parameters
  19. Return value
  20. Remarks
  21. Support and feedback
  22. IsNumeric VBA Function Checks if Cell is a Number
  23. The VBA Tutorials Blog
  24. Introduction to IsNumeric
  25. IsNumeric Examples
  26. Check if a Cell is a Number
  27. Check if All Cells in a Range are Numeric
  28. IsNumeric vs ISNUMBER
  29. Final Thoughts

Метод 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 и обратная связь.

Источник

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.

Источник

Функция 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 используется для определения того, может ли переменная быть оценена как число.

Источник

WorksheetFunction.IsNumber method (Excel)

Checks the type of value and returns True or False depending on whether the value refers to a number.

Syntax

expression.IsNumber (Arg1)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 Required Variant Value — the value that you want tested. Value can be a blank (empty cell), error, logical, text, number, or reference value, or a name referring to any of these, that you want to test.

Return value

Boolean

The value arguments of the IS functions are not converted. For example, in most other functions where a number is required, the text value 19 is converted to the number 19. However, in the formula ISNUMBER(«19») , 19 is not converted from a text value, and the IsNumber function returns False.

The IS functions are useful in formulas for testing the outcome of a calculation. When combined with the IF function, they provide a method for locating errors in formulas.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

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.

Источник

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 Not 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)

A cell with the time 3:00am

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;amp; Chr(10) &amp;amp;amp;amp;amp; x2 &amp;amp;amp;amp;amp; Chr(10) &amp;amp;amp;amp;amp; x3
End Sub

Run the macro and the answers will be displayed in the Msgbox:

msgbox stating False, False, True

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

Home / VBA / Top VBA Functions / VBA ISNUMERIC Function (Syntax + Example)

The VBA ISNUMERIC function is listed under the information category of VBA functions. When you use it in a VBA code, it evaluates the supplied expression and returns TRUE if it is a numeric value or else FALSE. In simple words, it can check whether the value supplied is a number or not and returns TRUE or FALSE based on that.

IsNumeric(Expression)

Arguments

  • Expression: An expression that you want to test if it’s numeric or not.

Example

To practically understand how to use the VBA ISNUMERIC function, you need to go through the below example where we have written a vba code by using it:

Sub example_ISNUMERIC()
Range("B1").Value = IsNumeric(Range("A1"))
End Sub

In the above code, we have used ISNUMERIC to check it the value in cell A1 is a number or not and it has returned TRUE in the result as we have 98 in cell A1.

Sub Excel_ISNUMBER_Function()

Dim ws As Worksheet

Set ws = Worksheets(«ISNUMBER»)

ws.Range(«C5») = Application.WorksheetFunction.IsNumber(ws.Range(«B5»))
ws.Range(«C6») = Application.WorksheetFunction.IsNumber(ws.Range(«B6»))
ws.Range(«C7») = Application.WorksheetFunction.IsNumber(ws.Range(«B7»))
ws.Range(«C8») = Application.WorksheetFunction.IsNumber(ws.Range(«B8»))
ws.Range(«C9») = Application.WorksheetFunction.IsNumber(ws.Range(«B9»))

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named ISNUMBER.

ADJUSTABLE PARAMETERS
Output Range: Select the output range by changing the cell references («C5») through to («C9») in the VBA code to any cell in the worksheet, that doesn’t conflict with the formula.

 

Здравствуйте!  
Вопрос, по сути в заголовке.    
Имеем значения, к примеру: «345» и «3куц» как в коде проще всего определить что можно использовать как число?    
Чет я простых методов не нашел… :(

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

Может я что-то не правильно понял?  
Debug.Print IsNumeric(Cells(1, 1).Value)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Понял ошибку. Я пробовал  Is Numeric.  
Спасибо!

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

Не за что  
Также:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=LightZ}{date=09.07.2012 07:29}{thema=}{post}Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»){/post}{/quote}С этим нужно осторожнее: при пустом значении и дате, получим неверные ответы :-)

 

Ну мне для решения конкретной задачи больше всего походит первый вариант в виде:  
If IsNumeric(Arr(i)) Then a = a + Arr(i)

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

Добрый вечер, Михаил!  
На всякий случай для коллекции, это тоже будет = True:  
Debug.Print IsNumeric(«1d3»), IsNumeric(«1e2»)

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Здравствуйте все. В дополнение, и это тоже:  
Debug.Print Application.IsText(«1d3»), Application.IsText(«1e2»)  
:-)

Я сам — дурнее всякого примера! …

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Забыл еще:  
Debug.Print Application.IsText(«13»), Application.IsText(«12»)

Я сам — дурнее всякого примера! …

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

Так я думаю вряд ли кто-то будет использовать  
с перемененными и константами всё Ок  

  Const x As Long = «111»: Const z As String = «abc»  
Debug.Print Application.IsText(x), Application.IsText(z)  

  False True

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Богдан, вот это — неправильно:  
Const x As Long = «111»  
Правильно:  
Const x As Long = 111  
Экс, да, произведет неявное преобразование, что не есть хорошо. Из-за того, что результат в разных случаях непредсказуем и может привести к ошибкам выполнения:-)  
Попробуй по шагам:  
Const x As Long = «1d3»  
Stop  
И посмотри, чему равен х.

Я сам — дурнее всякого примера! …

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

Серёж, а в чём разница то?  

  Const x As Long = «111»  
Const x As Long = 111

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

«111» — строка  
111 — число

 

{quote}{login=ZVI}{date=09.07.2012 09:56}{thema=}{post}Добрый вечер, Михаил!  
На всякий случай для коллекции, это тоже будет = True:  
Debug.Print IsNumeric(«1d3»), IsNumeric(«1e2»){/post}{/quote}  
А почему к «d» и «e» такое «избранное» отношение?  
Проверил другие буквы — везде False

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

{quote}{login=Юрий М}{date=09.07.2012 11:37}{thema=}{post}»111″ — строка  
111 — число{/post}{/quote} Ну это если не объявлять числовую переменную, тогда так

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Богдан, а тогда зачем объявлять заведомо неверно? Об этом Серж и говорит… Если «111», ту нужно и писать: As String. Если хотим числовую переменную — кавычки не нужны. Вот о чём разговор.

 

> А почему к «d» и «e» такое «избранное» отношение?  

  Михаил, это экспоненциальная запись числа. 1d3=1000, 1e2=100.  
В Фортране использование символа E означает тип Single, а D — Double. То есть там 1 — единица целого типа, 1E0 — единица типа Single, 1D0 — единица типа Double.  
VBA воспринимает обе буквы как указание типа Double.  
Попробуйте также в окне Immediate  

  ?isnumeric(«ff»),isnumeric(«&hff»),isnumeric(«&o75»),isnumeric(«&o79»)

 

Я попробовал так: хоть 234е765б + 1 хоть 123d765 + 1 =11 (+25 = 35)  
и вообще, т.е если внутри цифр, сколько бы из не было, стоит одна е или d, то как число это равно 10. но цифры должны быть с обеих сторон.

 

k61

Пользователь

Сообщений: 2441
Регистрация: 21.12.2012

IsNumeric(«ЧислоИлиЦифра» & Chr(160) & «ЧислоИлиЦифра»)=True  
Chr(160) — пробел.

 

Если данные будут считываться только из ячеек рабочего_листа:  

  Function ValueIsNumber(X) As Boolean  
   Select Case VarType(X)  
   Case vbDouble, vbDate, vbBoolean  
   Case Else  
       Exit Function  
   End Select  
   ValueIsNumber = True  
End Function  

  Если даты или логические не считать числами — удалить vbDate или vbBoolean

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

{quote}{login=Юрий М}{date=10.07.2012 10:40}{thema=}{post}Богдан, а тогда зачем объявлять заведомо неверно? Об этом Серж и говорит… Если «111», ту нужно и писать: As String. Если хотим числовую переменную — кавычки не нужны. Вот о чём разговор.{/post}{/quote}Юрий, я понял.  
По идее в варианте Михаила, данные будут заливаться с листа, т.е. проблем с IsNumeric или же IsText возникнуть не должно, у меня всегда отрабатывали на ура. :)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Если других данных не будет, то всё нормально. Весь сыр-бор разгорелся из-за того, что с проверкой типа есть подводные камни, и их желательно учитывать.

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

Загвоздочка может произойти только с пробелом или пустой ячейкой, т.к. vba считает, что пустая ячейка это число, а вот с датой проблем нет (false)  

  Dim x As Range  
   For Each x In ActiveSheet.UsedRange  
       If Not Application.Trim(x.Value) = Empty Then Debug.Print IsNumeric(x.Value), x.Value, x.Address  
   Next

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Что-то я не улавливаю.  
Если x.Value = Empty, то зачем Application.Trim ?  
Если x.Value <> Empty, то Application.Trim(x.Value) все равно не будет Empty

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=LightZ}{date=10.07.2012 10:01}{thema=}{post}Загвоздочка может произойти только с пробелом или пустой ячейкой, т.к. vba считает, что пустая ячейка это число, а вот с датой проблем нет {/post}{/quote}Ну как же нет?  
Вот Ваше предложение:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)  
Введите в ячейку дату и проверьте.

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

E — это экспоненциальная форма записи числа  
D — это тоже какая-то архаичная форма числа.  
И то и другое выдаст число As Double, возможно поэтому и D  

  В окне Immediate:  
?2d3 или ?2e3 покадут результат 2000, т.е 2*10^3  
?VarType(2e3)=vbDouble выдаст True  

  Если вписать в VBA-модуле, например, такую строку:  
a = 2d3 или a = 2e3  
то после смещения курсора на другую строку эта преобразуется в    
a = 2000#  
где # в конце означает преобразование числа в Double

 

Павел

Гость

#27

10.07.2012 22:23:57

2 Михаил С  

Цитата
А почему к «d» и «e» такое «избранное» отношение

Точка и знаки «d» и «e» могут быть частью записи числа, не поэтому ли?

 

LightZ

Пользователь

Сообщений: 1748
Регистрация: 22.12.2012

RAN, воспроизведите макрос:  
Sub tt()  
   With Cells(1, 1)  
       .Value = »   »  
       Debug.Print .Value = Empty, Application.Trim(.Value) = Empty  

                 .Value = Empty  
       Debug.Print .Value = Empty  
   End With  
End Sub  

  Т.е. с помощью Application.Trim(x.Value) убиваю сразу двух зайцев: пустоту и пробел  

  Юрий, я описал про IsNumeric, а с текстом придется учитывать и дату  

     With Cells(1, 1)  
       If Not IsDate(.Value) Then Debug.Print Application.IsText(.Value)  
   End With

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

{quote}{login=LightZ}{date=10.07.2012 10:29}{thema=}{post}Юрий, я описал про IsNumeric, а с текстом придется учитывать и дату{/post}{/quote}Я реагировал на это:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)  
Посмотрите — моё сообщение сразу после Вашего :-) Разобрались :-)

 

Михаил С.

Пользователь

Сообщений: 10514
Регистрация: 21.12.2012

#30

10.07.2012 23:15:44

Такой, казалось бы, простой вопрос, а столько подводных камней! :)  
Для моей задачи подошел самый первый ответ — IsNumeric(a).  
По сути у меня массив примерно 150 столбцов, с столбцы и числовые и тестовые. Нужно строки, удовлетворяющие определенным условиям, сложить, пропуская тест.  
такой кусок кодаЖ  
For ii =  1 To Ubound(Arr, 2)  
if IsNumeric(Arr(i, ii)) Then MiArr(si, ii) = MiArr(si, ii)+Arr(i, ii)  
Next  
Дат у меня нет, но проверил ради интереса — обрабатывает корректно, т.е. пропускает

Понравилась статья? Поделить с друзьями:
  • Excel vba if then else and or
  • Excel vba if textbox1
  • Excel vba if target column
  • Excel vba if sum of range
  • Excel vba if statements and