Excel vba is not numeric

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!

 

Здравствуйте!  
Вопрос, по сути в заголовке.    
Имеем значения, к примеру: «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  
Дат у меня нет, но проверил ради интереса — обрабатывает корректно, т.е. пропускает

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

VBA IsNumeric

VBA IsNumeric

IsNumber an excel function is used for identifying whether the cell content is a number or not. A numeric value can be a whole value or integer. An IsNumeric function can also be performed in VBA as well. In VBA this is available with the name “IsNumeric“. IsNumeric works in the same manner as IsNumber does. It analyzes the cell value and returns the answer whether it is a number or not.

IsNumeric considers only Boolean, which only gives result in the form of TRUE and FALSE.

Syntax of IsNumeric in Excel VBA

VBA IsNumeric has the following syntax in VBA:

Syntax of IsNumeric

How to Use Excel VBA IsNumeric?

We will learn how to use a VBA IsNumeric with few examples in excel.

You can download this VBA IsNumeric Excel Template here – VBA IsNumeric Excel Template

VBA IsNumeric – Example #1

Let’s see an easy example where we will select a cell with any content and in a separate cell, we will see whether cell content is a Number or Not.

Step 1: For this open, a new module in the VBA window under the Insert menu tab as shown below.

VBA IsNumeric Example 1-1

Step 2: Write a Subcategory in the name of a performed function or in any other name as shown below.

Code:

Sub VBA_Isnumeric1()

End Sub

VBA IsNumeric Example 1-2

Step 3: Now we will use the If-Else loop for this complete condition. For this open and close If bracket as shown below.

Code:

Sub VBA_Isnumeric1()

If

End If

End Sub

VBA IsNumeric Example 1-3

Step 4: Now in If write and select IsNumeric function and select any Range cell from where we will analyze the content. Here we have selected cell A1 as TRUE.

Code:

Sub VBA_Isnumeric1()

If IsNumeric(Range("A1")) = True Then

End If

End Sub

VBA IsNumeric Example 1-4

Step 5: If cell value at cell A1 is TRUE it means it is a number then we can choose writing any sentence in cell B1 which will say “It is a Number” or put any text as per your choice.

Code:

Sub VBA_Isnumeric1()

If IsNumeric(Range("A1")) = True Then
    Range("B1") = "It is a Number"
End If

End Sub

VBA IsNumeric Example 1-5

Step 6: Now in Else line of code consider writing what we could see when IF condition doesn’t work. We are selecting cell B1 where we will see the output statement of cell A1 as “It is not a Number” as shown below.

Code:

Sub VBA_Isnumeric1()

If IsNumeric(Range("A1")) = True Then
    Range("B1") = "It is a Number"
Else
    Range("B1") = "It is not a Number"
End If

End Sub

VBA IsNumeric Example 1-6

Step 7: Once done then compile and run the complete code. As we can see in the below screenshot for the cell content A1 we got the statement as “It is a Number” in cell B1.

Result of Example 1-7

Step 8: Now let’s replace 10 in cell A1 with a text like “Test” and see what we get.

VBA IsNumeric Example 1-8

Step 9: Now again run the complete code.

Result of Example 1-9

As we can see in the above screenshot, for the cell content A1 we got the statement as “It is not a number” for content “Test” which means cell A1 doesn’t have a number in it.

VBA IsNumeric – Example #2

There is another way to add IsNumeric. By far we all know that Boolean function is used for TRUE/ FALSE on the basis of what we feed and define the condition. Here we will use Boolean to calculate IsNumeric for any content of the cell.

Step 1: Write a Subcategory in the name of a performed function as shown below.

Code:

Sub VBA_IsNumeric2()

End Sub

VBA IsNumeric Example 2-1

Step 2: Now define a dimension “DIM” as A and assign it to Double. We can assign it as Integer or Long too. But that would only consider whole numbers and long text/numbers. Double is used where we are expecting to get numbers in decimal forms.

Code:

Sub VBA_IsNumeric2()

  Dim A As Double

End Sub

VBA IsNumeric Example 2-2

Step 3: Now define one more dimension “DIM” as X. And assign it as Boolean. We can consider any word, name or alphabet for defining dimensions in VBA.

Code:

Sub VBA_IsNumeric2()

  Dim A As Double
  Dim X As Boolean

End Sub

VBA IsNumeric Example 2-3

Step 4: Now for Dim A double, first assign the value as 10 which is a whole number.

Code:

Sub VBA_IsNumeric2()

  Dim A As Double
  Dim X As Boolean

  A = 10

End Sub

VBA IsNumeric Example 2-4

Step 5: Now for Boolean X, use IsNumeric function and assign defined Double A into the brackets of IsNumeric. By doing this IsNumeric will fetch the value stored in Dim A and analyze whether that value is a number or not.

Code:

Sub VBA_IsNumeric2()

  Dim A As Double
  Dim X As Boolean

  A = 10
  X = IsNumeric(A)

End Sub

VBA IsNumeric Example 2-5

Step 6: To get the answer of an analysis done by Isnumeric, we will assign it to a message box where we will see the result.

Code:

Sub VBA_IsNumeric2()

  Dim A As Double
  Dim X As Boolean

  A = 10
  X = IsNumeric(A)

MsgBox "The expression(10) is numeric or not : " & X, vbInformation, "VBA IsNumeric Function"

End Sub

VBA IsNumeric Example 2-6

Step 7: Once done compile and run the code.

Result of Example 2-7

As we can see a pop-up dialog box in the above image, the expression(10) is a TRUE numeric value.

Step 8: Now let’s change the value and put some decimal value in IsNumeric as shown below and see what output we get. Here we have to change the value of A as 10.12 and updated the message box with expression(10.12).

Code:

Sub VBA_IsNumeric2()

  Dim A As Double
  Dim X As Boolean

  A = 10.12
  X = IsNumeric(A)

MsgBox "The expression(10.12) is numeric or not : " & X, vbInformation, "VBA IsNumeric Function"

End Sub

VBA IsNumeric Example 2-8

Step 9: Now again compile and run the complete code.

Result of Example 2-9

We will again get TRUE for the value 10.12 which is a decimal value.

Step 10: Now let’s see if the current defined syntax of IsNumeric still works for other than numbers or not. For this, we need to change the Dim A as String which means we will be entering the Text value here. And change value entered for A. We have considered sample value as “ABC”. Make all necessary changes in related fields where we can place text instead of numbers and keep the rest of the things as it is.

Code:

Sub VBA_IsNumeric2()

  Dim A As String
  Dim X As Boolean

  A = ABC
  X = IsNumeric(A)

MsgBox "The expression('ABC') is numeric or not : " & X, vbInformation, "VBA IsNumeric Function"

End Sub

Example 2-10

Step 11: After that compile and run the complete code.

Result of Example 2-11

Pros of Excel VBA IsNumeric

  • It is so easy to apply IsNumeric in VBA. It is as simple as applying Isnumber through insert function.
  • IsNumeric and IsNumber give the same result.

Cons of Excel VBA IsNumeric

  • Applying example-2 where we need to insert text makes the simple process lengthy.

Things To Remember

  • Recording a macro is also a way to perform IsNumeric function in VBA.
  • Save the file in Macro-Enabled Excel, This is the best way to avoid losing written code.
  • Best way to avoid any error while running the code is to first compile the complete code before we fix it as final.
  • Assigning the created code into a button is also a way to perform created macro quickly, this saves time.
  • If you are applying IsNumeric by example-2 method then remember to keep text in the single quote (‘Text’) otherwise it will give an error.
  • As IsNumeric in VBA is used, in excel it used in the name of IsNumber.

Recommended Articles

This has been a guide to VBA IsNumeric. Here we discussed how to use Excel VBA IsNumeric along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Dim
  2. VBA RGB
  3. VBA IFError
  4. VBA Login

VBA IsNumeric function in Excel is categorized as an Information function in VBA. It is a built-in function in MS Office Excel VBA. This function checks specified Expression is Numeric or not. It has one input parameter. It returns boolean value (True or False).

The IsNumeric function can be used only in VBA. We can’t use this function as a worksheet function. This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA IsNumeric function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the IsNumeric function, where we can use this VBA IsNumeric function and real-time examples.

Table of Contents:

  • Overview
  • Syntax of VBA IsNumeric Function
  • Parameters or Arguments
  • Where we can apply or use VBA IsNumeric Function?
  • Example 1: Check an expression(100) is numeric or not
  • Example 2: Check given expression(100.123) is numeric or not
  • Example 3: Check an expression(“ABC”) is numeric or not
  • Example 4: Check an expression(“ABC123”) is numeric or not
  • Example 5: Check an expression(TRUE) is numeric or not
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA IsNumeric function is

IsNumeric(Expression)

Note: The VBA IsNumeric function returns a boolean value.

Parameters or Arguments

The IsNumeric function has one input parameter or argument.
Where
Expression: It is a required parameter. The Expression that you want to evaluate.

Where we can apply or use VBA IsNumeric Function?

We can use this VBA IsNumeric function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Check an expression(100) is numeric or not

Here is a simple example of the VBA IsNumeric function. This below example checks the specified number(100) is numeric or not. The output of below macro is TRUE.

'Check an expression(100) is numeric or not
Sub VBA_IsNumeric_Function_Ex1()
    
    'Variable declaration
    Dim iExpression As Integer
    Dim sOutput As Boolean
    
    iExpression = 100
    
    sOutput = IsNumeric(iExpression)
   
    'Display output message
    MsgBox "The expression(100) is numeric or not : " & sOutput, vbInformation, "VBA IsNumeric Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA IsNumeric Function

Example 2: Check given expression(100.123) is numeric or not

Here is another example of the VBA IsNumeric function. This below example checks the specified number(100.123) is numeric or not. The output of below macro is TRUE.

'Check given expression(100.123) is numeric or not
Sub VBA_IsNumeric_Function_Ex2()
    
    'Variable declaration
    Dim iExpression As Double
    Dim sOutput As Boolean
    
    iExpression = 100.123
    
    sOutput = IsNumeric(iExpression)
   
    'Display output message
    MsgBox "The expression(100.123) is numeric or not : " & sOutput, vbInformation, "VBA IsNumeric Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA IsNumeric Function

Example 3: Check an expression(“ABC”) is numeric or not

Here is a simple example of the VBA IsNumeric function. This below example checks the specified number(“ÄBC”) is numeric or not. The output of below macro returns False.

'Check an expression("ABC") is numeric or not
Sub VBA_IsNumeric_Function_Ex3()
    
    'Variable declaration
    Dim iExpression As String
    Dim sOutput As Boolean
    
    iExpression = "ÄBC"
    
    sOutput = IsNumeric(iExpression)
   
    'Display output message
    MsgBox "The expression('ABC') is numeric or not : " & sOutput, vbInformation, "VBA IsNumeric Function"
    
End Sub 

Output:Here is the screen shot of the third example output.
VBA IsNumeric Function

Example 4: Check an expression(“ABC123”) is numeric or not

Here is a simple example of the VBA IsNumeric function. This below example checks the specified number(“ABC123”) is numeric or not. The output of below macro is False.

'Check an expression("ABC123") is numeric or not
Sub VBA_IsNumeric_Function_Ex4()
    
    'Variable declaration
    Dim iExpression As String
    Dim sOutput As Boolean
    
    iExpression = "ÄBC123"
    
    sOutput = IsNumeric(iExpression)
   
    'Display output message
    MsgBox "The expression('ABC123') is numeric or not : " & sOutput, vbInformation, "VBA IsNumeric Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA IsNumeric Function

Example 5: Check an expression(TRUE) is numeric or not

Here is a simple example of the VBA IsNumeric function.This below example checks the specified number(TRUE) is numeric or not. The output of below macro is TRUE.

'Check an expression(TRUE) is numeric or not
Sub VBA_IsNumeric_Function_Ex5()
    
    'Variable declaration
    Dim iExpression As Boolean
    Dim sOutput As Boolean
    
    iExpression = True
    
    sOutput = IsNumeric(iExpression)
   
    'Display output message
    MsgBox "The expression(TRUE) is numeric or not : " & sOutput, vbInformation, "VBA IsNumeric Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA IsNumeric Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Понравилась статья? Поделить с друзьями:
  • Excel vba is keyword
  • Excel vba now time
  • Excel vba is decimal
  • Excel vba not select cell
  • Excel vba is cell merge