Excel vba if cell is not 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!

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.

  • #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

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  является значение ячейки числом или же это текст.
использую
If Cells(1, 1) > 0 Then
но не всегда корректно работает

 

hk1209

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

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

#2

18.09.2014 16:26:37

можно создать формулу, затем проверить, содержит ли, например, A2, число или текст, =HaveNumbers(A2)

Код
Function HaveNumbers(oRng As Range) As Boolean 
   Dim bHaveNumbers As Boolean, i As Long 
   bHaveNumbers = False 
      For i = 1 To Len(oRng.Text) 
      If IsNumeric(Mid(oRng.Text, i, 1)) Then 
         bHaveNumbers = True 
         Exit For 
      End If 
     Next 
    HaveNumbers = bHaveNumbers 
End Function 
 

IsNumeric — точно.
Спасибо!!!

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Только учтите, что вместе с IsNumeric лучше так же использовать
If not Cells(1,1).Vaue <> «» then
т.к. IsNumeric в большинстве случаев пустую ячейку считает нулем…

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 
 

Kuzmich

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

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

Надо еще учесть, что даты тоже числа.

 

Слава богу, в моем случае этого учитывать не нужно.

Извините за ОФФ. я конечно давно зарегистрировался, уже не вспомнить, но…  Регистрация: 1 Янв 1970, — я ж тогда ещё и не родился.  :)

 

Dolphin

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

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

#8

18.09.2014 17:16:19

Код
Function HaveNumbers(oRng As Range) As Boolean
    With CreateObject("VBScript.RegExp")
        .Pattern = "^d+$"
        With .Execute(oRng.Value)
            HaveNumbers = .Count > 0
        End With
    End With
End Function 

Изменено: Dolphin18.09.2014 17:19:59
(Подправил макрос.)

There is no knowledge that is not power

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

#9

18.09.2014 17:40:34

Цитата
Kuzmich пишет: Надо еще учесть, что даты тоже числа

Если формат ячейки установлен для Дат — то IsNumeric не будет считать дату числом. Это актуально только если формат ячеек общий. Но в этом случае все будет правильно — ведь дата тогда и отображаться будет как число…

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

есть ещё одна ошибка с объединенными ячейками
код выдает ошибку
Cells(y,iKol) = <application-defined or object — defined error>
нужно чтобы програмка понимала что там нет числа

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Очень описательно.
Скорее всего дело не в объединенной ячейке, а в том, что внутри ячейки — значение ошибки.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Николай Юманов

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

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

#12

19.09.2014 14:25:47

Цитата
The_Prist пишет: Скорее всего дело не в объединенной ячейке

Точно! Дело было не в бабине… значение переменной iKol я задал через Inputbox вроде цифры, но в кавычках.   :oops:

<#0>

 

Сливочный

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

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

Win 10, MSO 2016

Здравствуйте!

Перед занесением диапазона в массив воткнул проверку всех значений диапазона через цикл FOR-NEXT, на отсутствие отрицательных чисел и не чисел, дак вот почему-то при проверке на не числа редактор выделяет isnumeric и останавливается.
Подскажите пожалуйста, почему выдаёт ошибку, что нужно исправить? Может я путь не правильно указал? Слышал можно подсказки самого редактора смотреть, как это сделать?

 

Юрий М

Модератор

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

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

#14

01.08.2016 12:26:08

Цитата
Сливочный написал:
Может я путь не правильно указал?

А путь тут причём? )) Покажите код, лучше вместе с небольшим файлом-примером.

 

Сливочный

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

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

Win 10, MSO 2016

Юрий М, прошу прощения, забыл прикрепить файл. Макрос в котором ошибка — myarray

а нет не забыл оказывается, что не так? файл-пример уменьшить?

Изменено: Сливочный01.08.2016 12:33:07

 

Юрий М

Модератор

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

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

А зачем там Is Nothing? Удалите это.

 

Сливочный

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

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

Win 10, MSO 2016

Юрий М, надо проверить, если проверяемое значение не число или число но меньше 0, выйти из макроса.  

 

Юрий М

Модератор

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

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

#18

01.08.2016 12:46:06

Я же говорил — Nothig уберите:

Код
If Not IsNumeric(Range("A1")) Or Range("A1") < 0 Then
        Exit Sub
    Else
        MsgBox "Продолжаем работу"
    End If
 

Сливочный

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

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

Win 10, MSO 2016

#19

01.08.2016 12:55:53

Юрий М, всё работает, спасибо!

Содержание

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

Источник

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.

Понравилась статья? Поделить с друзьями:
  • Excel vba if cell is colored
  • Excel vba if array is not empty
  • Excel vba if any value in range
  • Excel vba if any cell in range
  • Excel vba method open of object workbooks failed