Excel vba if value is integer

TommyGun

TommyGun

MrExcel MVP

Joined
Dec 9, 2002
Messages
4,202


  • #2

<font face=Courier New><SPAN style=»color:#00007F»>Sub</SPAN> Test()
    <SPAN style=»color:#00007F»>Dim</SPAN> i <SPAN style=»color:#00007F»>As</SPAN> <SPAN style=»color:#00007F»>Integer</SPAN>, j <SPAN style=»color:#00007F»>As</SPAN> <SPAN style=»color:#00007F»>Long</SPAN>

    
    i = 250
    j = 2500000

    
    <SPAN style=»color:#00007F»>If</SPAN> TypeName(i) = «Integer» <SPAN style=»color:#00007F»>Then</SPAN>
        MsgBox «Variable «»i»» is an integer.»
    <SPAN style=»color:#00007F»>Else</SPAN>
        MsgBox «Variable «»i»» is a: » & TypeName(i)
    <SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>If</SPAN>

    
    <SPAN style=»color:#00007F»>If</SPAN> TypeName(j) = «Integer» <SPAN style=»color:#00007F»>Then</SPAN>
        MsgBox «Variable «»j»» is an integer.»
    <SPAN style=»color:#00007F»>Else</SPAN>
        MsgBox «Variable «»j»» is a: » & TypeName(j)
    <SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>If</SPAN>
<SPAN style=»color:#00007F»>End</SPAN> <SPAN style=»color:#00007F»>Sub</SPAN></FONT>

tzenekkik

New Member

Joined
Jun 3, 2002
Messages
39


  • #3

or try this: =TRUNC(A1;0)=A1
(provided A1 holds the value to be tested)

Scott Huish

Scott Huish

MrExcel MVP

Joined
Mar 17, 2004
Messages
19,961
Office Version
  1. 365
Platform
  1. Windows


  • #4

Sub test()
x = Range(«A1»).Value
If Int(x) / x = 1 Then
MsgBox «Value is an Integer»
Else
MsgBox «Value is not an Integer»
End If
End Sub

RalphA

Well-known Member

Joined
May 14, 2003
Messages
3,829


  • #5

One more:

Assuming A1 has the number, put, in any other cell, the formula:
=IF(INT(A1)=A1,»True»,»False»)

tzenekkik

New Member

Joined
Jun 3, 2002
Messages
39


  • #6

so: INT(A1)=A1 is the shortest version to test for an integer.

verblender

New Member

Joined
May 15, 2017
Messages
1


  • #7

since you are using VBA, not checking within the formulas of a given worksheet, you can check if a cell is of integer variable type using this syntax:

If

VarType(my_variable) = vbInteger Then ‘IF my_variable if is of type Integer …

other types of comparisons for different kinds of data (date, text, etc) can be made using the following code:

If VarType(my_variable) = vbInteger Then ‘IF my_variable is of type Integer …
‘Identical to :
If VarType(my_variable) = 2 Then ‘IF my_variable is of type Integer …

based on the following table:

vbEmpty 0
vbNull 1
vbInteger 2
vbLong 3
vbSingle 4
vbDouble 5
vbCurrency 6
vbDate 7
vbString 8
vbObject 9
vbError 10

i read this on from https://www.excel-pratique.com/en/vba/conditions_continued.php which basically covers this for VBA.

SpillerBD

Well-known Member

Joined
Jul 2, 2014
Messages
2,851
Office Version
  1. 365
Platform
  1. Windows


  • #8

=If (Trunc(A1)=A1,Integer,Non-Integer)
or
=If (Int(A1)=A1,Integer,Non-Integer)

I wouldn’t be surprised if the «math» and the floating point issues have some of these fail.

In VBA, you have INT function.
The other functions are available through WorksheetFunction

cubitmg

New Member

Joined
Feb 18, 2023
Messages
1
Office Version
  1. 2016
Platform
  1. Windows


  • #9

If you can use a macro then I find this function works:
Public Function isInteger(varValue)
On Error GoTo Exit_isInteger ‘if not numeric then int() will throw an error and take the default False return value
isInteger = False ‘default False return value
If Int(varValue) = Val(varValue) Then isInteger = True
Exit_isInteger:
End Function

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!

When you pass a numeric value from Excel to VBA, the value is always passed as Double, therefore the check for VarType will not work.

Try the following function: It first checks if the value is numeric at all. If yes, it checks if the integer-part of the number is equal to the number itself. It uses CLng to avoid numeric overflows.

Function isInteger(c As Variant) As Boolean
    If Not IsNumeric(c) Then Exit Function
    isInteger = (c = CLng(c))
End Function

Update After freeflow’s comment, I did some tests, see image.
It seems that the formatting of a cell doesn’t impact the type that is passed to VBA — except if it is a Date. The number 44614 shown as value is in fact the formula =Today() (so today’s date, without time). Only when the cell is formatted as Date, the value is passed as a Date rather than a number.
In all cases, when a number is passed, it is passed as Double.
The column IsInteger shows the result of the Function above.

(With passed I mean that a variant is passed containing a vartype of…)

enter image description here

В языке VBA есть универсальные типы данных, т.е. способные хранить как число, так и строку, дату и любой другой тип информации. Например, ячейка в таблице может содержать что угодно и изначально, программа не знает какой в ней тип данных хранится. Кроме того, в самой программе может использоваться тип данных Variant, который так же может содержать любое значение любого типа.

Чтобы определить какой тип данных в ячейке или в переменной типа Variant, можно воспользоваться несколькими способами.

Способ 1. Использовать функцию TypeName для определения типа данных

Эта функция возвращает строку с названием типа данных на английском. В качестве аргумента принимает переменную, значение ячейки.
Обратите внимание: Функция определяет только стандартные типы данных и не может определить пользовательский тип (определенный с помощью Type).

Возможные возвращаемые функцией значения:

Byte Число типа Byte
Integer Целое число
Long Длинное целое число
Single Число одиночной точности с плавающей запятой
Double Число двойной точности с плавающей запятой
Currency Валюта
Decimal Число с плавающей запятой
Date Дата
String Строка
Boolean Логическое
Error Ошибка
Empty Не проинициализировано (т.е. переменная не была объявлена)
Null Неверные данные (в переменной нет корректных данных)
Object Объект (класс)
Unknown Тип данных не известен
Nothing Объект, никуда не ссылающийся

Приведу несколько примеров по использованию TypeName.

Пример 1. Определение типа переменной.

Dim v As Integer
MsgBox TypeName(v) ' Выведет: Integer

Обратите внимание: если вы используете результат TypeName в условии, т.е. проверяете, соответствует ли тип данных определенному, например, Integer, то регистр символов возвращаемого типа имеет значение. Т.е. нужно писать Integer с заглавной буквы, либо использовать приведение всех символов к одному регистру.

Пример 2. Использование TypeName в условии.

Dim v As Integer
If TypeName(v) = "Integer" Then MsgBox "Yes" Else MsgBox "No"         ' Yes
If TypeName(v) = "integer" Then MsgBox "Yes" Else MsgBox "No"         ' No
If LCase(TypeName(v)) = "integer" Then MsgBox "Yes" Else MsgBox "No"  ' Yes

Пример 3. Определение типа данных в ячейке.

MsgBox TypeName(Cells(1, 1).Value) ' Выведет тип данных в ячейке A1

Если функции была передана переменная массив, она вернет тип данных в массиве с добавлением скобок.

Пример 4. Определение типа массива.

Dim Arr1(10) As Integer
Dim Arr2(10)
MsgBox TypeName(Arr1) ' Выведет: Integer()
MsgBox TypeName(Arr2) ' Выведет: Variant()

Способ 2. Проверка на возможность преобразования строки к нужному типу.

Бывает ситуация, когда значение, например, число или дата, содержится в строке. В этом случае TypeName вернет String, а не Integer или Date. Чтобы узнать, что содержится в строке, можно воспользоваться одной из функций IsNumeric, IsDate, IsObject, IsArray, IsNull, IsError.

IsNumeric Проверяет может ли выражение быть преобразовано в число
IsDate Проверяет может ли выражение быть преобразовано в дату
IsObject Проверяет, является ли переменная объектом
IsArray Проверяет, является ли переменная массивом
IsNull Проверка на пустое значение
IsError Проверка выражения на ошибку

Пример 4. Определение может ли переменная быть преобразована в число.

Dim v As String
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no (т.к. в строке нет числа)
v = "120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
v = "120.45"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "test 120"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no
v = "120 test"
If IsNumeric(v) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

К сожалению, как видим из примера, нет возможности проверить, содержится ли в строке число с плавающей точкой.

Пример 5. Определение содержит ли переменная дату (может быть преобразована в дату).

Dim firstDate, secondDate As Date
Dim timeOnly, dateAndTime, noDate As String
firstDate = CDate("12.05.2017")
secondDate = #12/5/2017#
timeOnly = "15:45"
dateAndTime = "12.05.2017 15:45"
noDate = "Test"
If IsDate(firstDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(secondDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(timeOnly) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(dateAndTime) Then MsgBox "yes" Else MsgBox "no" ' Выведет: yes
If IsDate(noDate) Then MsgBox "yes" Else MsgBox "no" ' Выведет: no

Проверка, содержится ли число или дата в ячейке листа делается аналогично, как и с переменными.

Помимо этих способов можно конечно еще придумать и другие, например, проверку строки с данными регулярным выражением или пройти по каждому символу в цикле и проверить цифра это или нет и тому подобное. Но на мой взгляд, описанных мной способов вполне достаточно для решения повседневных задач.

  1. 08-03-2006, 09:50 AM


    #1

    Check if a value is an integer using VBA code

    I know I should be able ot do this but I’m drawing a blank and nothing seems
    to be working. I want to check a series of user entered values in a vertical
    range, see if they are integers, and place them in a 1D integer array. If
    they are not postive integers, the array values will be set to zero ( the
    range values can remain whatever they are).

    How can I do this?


  2. 08-03-2006, 10:45 AM


    #2

    RE: Check if a value is an integer using VBA code

    Sub MakeArray()
    Dim arr() as Long
    Dim i as Long
    redim arr(1 to selection.count)
    i = 0
    for each cell in selection
    i = i + 1
    arr(i) = 0
    if isnumeric(cell) then
    if int(cell) = cell then
    if int(cell) >= 0 then
    arr(i) = cell
    end if
    end if
    end if
    Next
    End sub


    Regards,
    Tom Ogilvy

    «Rayo K» wrote:


    > I know I should be able ot do this but I’m drawing a blank and nothing seems
    > to be working. I want to check a series of user entered values in a vertical
    > range, see if they are integers, and place them in a 1D integer array. If
    > they are not postive integers, the array values will be set to zero ( the
    > range values can remain whatever they are).
    >
    > How can I do this?


  3. 08-03-2006, 11:30 AM


    #3

    RE: Check if a value is an integer using VBA code

    Thanks,

    I had come up this workaround since y is initially a variant, but the
    isnumeric is what I was really looking for.

    If VarType(y) > 1 And VarType(y) < 6 Then
    y = CInt(y)
    If y > 0 Then
    copies(x) = y
    Else: copies(x) = 0
    End If
    Else: copies(x) = 0
    End If

    «Tom Ogilvy» wrote:


    > Sub MakeArray()
    > Dim arr() as Long
    > Dim i as Long
    > redim arr(1 to selection.count)
    > i = 0
    > for each cell in selection
    > i = i + 1
    > arr(i) = 0
    > if isnumeric(cell) then
    > if int(cell) = cell then
    > if int(cell) >= 0 then
    > arr(i) = cell
    > end if
    > end if
    > end if
    > Next
    > End sub
    >
    > —
    > Regards,
    > Tom Ogilvy
    >
    > «Rayo K» wrote:
    >
    > > I know I should be able ot do this but I’m drawing a blank and nothing seems
    > > to be working. I want to check a series of user entered values in a vertical
    > > range, see if they are integers, and place them in a 1D integer array. If
    > > they are not postive integers, the array values will be set to zero ( the
    > > range values can remain whatever they are).
    > >
    > > How can I do this?


  4. 08-03-2006, 11:35 AM


    #4

    RE: Check if a value is an integer using VBA code

    Thanks,

    I had come up this workaround since y is initially a variant, but the
    isnumeric is what I was really looking for.

    If VarType(y) > 1 And VarType(y) < 6 Then
    y = CInt(y)
    If y > 0 Then
    copies(x) = y
    Else: copies(x) = 0
    End If
    Else: copies(x) = 0
    End If

    «Tom Ogilvy» wrote:


    > Sub MakeArray()
    > Dim arr() as Long
    > Dim i as Long
    > redim arr(1 to selection.count)
    > i = 0
    > for each cell in selection
    > i = i + 1
    > arr(i) = 0
    > if isnumeric(cell) then
    > if int(cell) = cell then
    > if int(cell) >= 0 then
    > arr(i) = cell
    > end if
    > end if
    > end if
    > Next
    > End sub
    >
    > —
    > Regards,
    > Tom Ogilvy
    >
    > «Rayo K» wrote:
    >
    > > I know I should be able ot do this but I’m drawing a blank and nothing seems
    > > to be working. I want to check a series of user entered values in a vertical
    > > range, see if they are integers, and place them in a 1D integer array. If
    > > they are not postive integers, the array values will be set to zero ( the
    > > range values can remain whatever they are).
    > >
    > > How can I do this?


  5. 08-03-2006, 11:50 AM


    #5

    RE: Check if a value is an integer using VBA code

    As long as you recognize that cint rounds the number

    ? cint(5.6)
    6

    You said if it is an integer, not make it an integer. But you know what you
    want (but perhaps not how to say it) better than I.


    regards,
    Tom Ogilvy

    «Rayo K» wrote:


    > Thanks,
    >
    > I had come up this workaround since y is initially a variant, but the
    > isnumeric is what I was really looking for.
    >
    > If VarType(y) > 1 And VarType(y) < 6 Then
    > y = CInt(y)
    > If y > 0 Then
    > copies(x) = y
    > Else: copies(x) = 0
    > End If
    > Else: copies(x) = 0
    > End If
    >
    > «Tom Ogilvy» wrote:
    >
    > > Sub MakeArray()
    > > Dim arr() as Long
    > > Dim i as Long
    > > redim arr(1 to selection.count)
    > > i = 0
    > > for each cell in selection
    > > i = i + 1
    > > arr(i) = 0
    > > if isnumeric(cell) then
    > > if int(cell) = cell then
    > > if int(cell) >= 0 then
    > > arr(i) = cell
    > > end if
    > > end if
    > > end if
    > > Next
    > > End sub
    > >
    > > —
    > > Regards,
    > > Tom Ogilvy
    > >
    > > «Rayo K» wrote:
    > >
    > > > I know I should be able ot do this but I’m drawing a blank and nothing seems
    > > > to be working. I want to check a series of user entered values in a vertical
    > > > range, see if they are integers, and place them in a 1D integer array. If
    > > > they are not postive integers, the array values will be set to zero ( the
    > > > range values can remain whatever they are).
    > > >
    > > > How can I do this?


  6. 08-03-2006, 04:00 PM


    #6

    RE: Check if a value is an integer using VBA code

    I did want to pass the number on only if it was an integer. The line that
    forced it to be an integer was a compromise because VarType was returning
    actual integers as longs, so the code was assuming there were no integers at
    all. But using IsNumeric solved that problem.

    «Tom Ogilvy» wrote:


    > As long as you recognize that cint rounds the number
    >
    > ? cint(5.6)
    > 6
    >
    > You said if it is an integer, not make it an integer. But you know what you
    > want (but perhaps not how to say it) better than I.
    >
    > —
    > regards,
    > Tom Ogilvy
    >
    >
    > «Rayo K» wrote:
    >
    > > Thanks,
    > >
    > > I had come up this workaround since y is initially a variant, but the
    > > isnumeric is what I was really looking for.
    > >
    > > If VarType(y) > 1 And VarType(y) < 6 Then
    > > y = CInt(y)
    > > If y > 0 Then
    > > copies(x) = y
    > > Else: copies(x) = 0
    > > End If
    > > Else: copies(x) = 0
    > > End If
    > >
    > > «Tom Ogilvy» wrote:
    > >
    > > > Sub MakeArray()
    > > > Dim arr() as Long
    > > > Dim i as Long
    > > > redim arr(1 to selection.count)
    > > > i = 0
    > > > for each cell in selection
    > > > i = i + 1
    > > > arr(i) = 0
    > > > if isnumeric(cell) then
    > > > if int(cell) = cell then
    > > > if int(cell) >= 0 then
    > > > arr(i) = cell
    > > > end if
    > > > end if
    > > > end if
    > > > Next
    > > > End sub
    > > >
    > > > —
    > > > Regards,
    > > > Tom Ogilvy
    > > >
    > > > «Rayo K» wrote:
    > > >
    > > > > I know I should be able ot do this but I’m drawing a blank and nothing seems
    > > > > to be working. I want to check a series of user entered values in a vertical
    > > > > range, see if they are integers, and place them in a 1D integer array. If
    > > > > they are not postive integers, the array values will be set to zero ( the
    > > > > range values can remain whatever they are).
    > > > >
    > > > > How can I do this?


  7. 08-03-2006, 04:45 PM


    #7

    RE: Check if a value is an integer using VBA code

    You said your users placed the values in cells as I recall. All values in
    cells are stored as double — whether whole numbers or not.

    Perhaps it doesn’t make any difference, but using vartype isn’t going to
    work for values extracted from cells.

    from the immediate window printing out the cell value and the results of
    vartype on a variant variable that was assigned that value
    Value Vartype result
    1 5
    2 5
    3 5
    5.5 5
    4.5 5


    Regards,
    Tom Ogilvy

    «Rayo K» wrote:


    > I did want to pass the number on only if it was an integer. The line that
    > forced it to be an integer was a compromise because VarType was returning
    > actual integers as longs, so the code was assuming there were no integers at
    > all. But using IsNumeric solved that problem.
    >
    > «Tom Ogilvy» wrote:
    >
    > > As long as you recognize that cint rounds the number
    > >
    > > ? cint(5.6)
    > > 6
    > >
    > > You said if it is an integer, not make it an integer. But you know what you
    > > want (but perhaps not how to say it) better than I.
    > >
    > > —
    > > regards,
    > > Tom Ogilvy
    > >
    > >
    > > «Rayo K» wrote:
    > >
    > > > Thanks,
    > > >
    > > > I had come up this workaround since y is initially a variant, but the
    > > > isnumeric is what I was really looking for.
    > > >
    > > > If VarType(y) > 1 And VarType(y) < 6 Then
    > > > y = CInt(y)
    > > > If y > 0 Then
    > > > copies(x) = y
    > > > Else: copies(x) = 0
    > > > End If
    > > > Else: copies(x) = 0
    > > > End If
    > > >
    > > > «Tom Ogilvy» wrote:
    > > >
    > > > > Sub MakeArray()
    > > > > Dim arr() as Long
    > > > > Dim i as Long
    > > > > redim arr(1 to selection.count)
    > > > > i = 0
    > > > > for each cell in selection
    > > > > i = i + 1
    > > > > arr(i) = 0
    > > > > if isnumeric(cell) then
    > > > > if int(cell) = cell then
    > > > > if int(cell) >= 0 then
    > > > > arr(i) = cell
    > > > > end if
    > > > > end if
    > > > > end if
    > > > > Next
    > > > > End sub
    > > > >
    > > > > —
    > > > > Regards,
    > > > > Tom Ogilvy
    > > > >
    > > > > «Rayo K» wrote:
    > > > >
    > > > > > I know I should be able ot do this but I’m drawing a blank and nothing seems
    > > > > > to be working. I want to check a series of user entered values in a vertical
    > > > > > range, see if they are integers, and place them in a 1D integer array. If
    > > > > > they are not postive integers, the array values will be set to zero ( the
    > > > > > range values can remain whatever they are).
    > > > > >
    > > > > > How can I do this?


Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.

Проверка переменных и выражений

Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.

Синтаксис функций для проверки переменных и выражений:

Expression — выражение, переменная или необязательный аргумент для IsMissing.

Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.

Функция IsArray

Описание функции

Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:

  • True — переменная является массивом;
  • False — переменная не является массивом.

Пример с IsArray

Sub Primer1()

Dim arr1(), arr2(1 To 10), arr3

    Debug.Print IsArray(arr1)  ‘Результат: True

    Debug.Print IsArray(arr2)  ‘Результат: True

    Debug.Print IsArray(arr3)  ‘Результат: False

arr3 = Array(1, 2, 3, 4, 5)

    Debug.Print IsArray(arr3)  ‘Результат: True

End Sub

Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.

Функция IsDate

Описание функции

Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:

  • True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
  • False — в иных случаях.

Пример с IsDate

Sub Primer2()

Dim d1 As String, d2 As Date

    Debug.Print IsDate(d1)  ‘Результат: False

    Debug.Print IsDate(d2)  ‘Результат: True

d1 = «14.01.2023»

    Debug.Print IsDate(d1)  ‘Результат: True

    Debug.Print IsDate(Now)  ‘Результат: True

End Sub

Функция IsEmpty

Описание функции

Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:

  • True — переменная содержит значение Empty;
  • False — переменной присвоено значение, отличное от Empty.

Пример с IsEmpty

Sub Primer3()

Dim s As String, v As Variant

    Debug.Print IsEmpty(s)  ‘Результат: False

    Debug.Print IsEmpty(v)  ‘Результат: True

v = 125

    Debug.Print IsEmpty(v)  ‘Результат: False

Range(«A1»).Clear

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: True

Range(«A1») = 123

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: False

End Sub

Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).

Функция IsError

Описание функции

Функция IsError возвращает логическое значение, указывающее, является ли аргумент функции значением ошибки, определенной пользователем:

  • True — аргумент функции является значением ошибки, определенной пользователем;
  • False — в иных случаях.

Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.

Пример с IsError

Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:

Function Vkuba(x)

    If IsNumeric(x) Then

        Vkuba = x ^ 3

    Else

        Vkuba = CVErr(25)

    End If

End Function

Sub Primer4()

    Debug.Print Vkuba(5)  ‘Результат: 125

    Debug.Print IsError(Vkuba(5))  ‘Результат: False

    Debug.Print Vkuba(«пять»)  ‘Результат: Error 25

    Debug.Print IsError(Vkuba(«пять»))  ‘Результат: True

End Sub

Функция IsMissing

Описание функции

Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:

  • True — если в процедуру не было передано значение для необязательного аргумента;
  • False — значение для необязательного аргумента было передано в процедуру.

Пример с IsMissing

Function Scepka(x, Optional y)

    If Not IsMissing(y) Then

        Scepka = x & y

    Else

        Scepka = x & » (а необязательный аргумент не подставлен)»

    End If

End Function

Sub Primer5()

    Debug.Print Scepka(«Тропинка», » в лесу»)  ‘Результат: Тропинка в лесу

    Debug.Print Scepka(«Тропинка»)  ‘Результат: Тропинка (а необязательный аргумент не подставлен)

End Sub

Функция IsNull

Описание функции

Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:

  • True — значением переменной или выражения является Null;
  • False — в иных случаях.

Пример с IsNull

Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:

Sub Primer6()

Dim Var

Var = Null

    If Var = Null Then Debug.Print Var  ‘Результат: «»

    If Var <> Null Then Debug.Print Var  ‘Результат: «»

    If IsNull(Var) Then Debug.Print Var  ‘Результат: Null

End Sub

Функция IsNumeric

Описание функции

Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:

  • True — если аргумент функции может рассматриваться как число;
  • False — в иных случаях.

Пример с IsNumeric

Sub Primer7()

Debug.Print IsNumeric(«3,14»)  ‘Результат: True

Debug.Print IsNumeric(«четыре»)  ‘Результат: False

End Sub

Функция IsObject

Описание функции

Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:

  • True — переменная содержит ссылку на объект или значение Nothing;
  • False — в иных случаях.

Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.

Пример с IsObject

Sub Primer8()

Dim myObj As Object, myVar As Variant

    Debug.Print IsObject(myObj)  ‘Результат: True

    Debug.Print IsObject(myVar)  ‘Результат: False

Set myVar = ActiveSheet

    Debug.Print IsObject(myVar)  ‘Результат: True

End Sub


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • Check if value is an integer in VBA

  1. Sep 24th, 2004, 01:57 PM


    #1

    jonx is offline

    Thread Starter


    Member


    Check if value is an integer in VBA

    How would i check to see if a value i have is an integer?

    For example, when i am grabbing values off an excel worksheet, sometimes the value is a 2, or 3 or whatever. But, once and a while, the value is N/A which means that my program would crash
    because you can’t do calculations to a the string «N/A»

    I was thinking about doing something like

    if value is an integer then
    perform calcuations
    end if

    how would i do this?


  2. Sep 24th, 2004, 02:16 PM


    #2

    robymix is offline


    Addicted Member


    I’ve not used VBA before. In VB you could do this:

    VB Code:

    1. If IsNumeric(value) Then

    2.     'your code here

    3. End If


  3. Sep 24th, 2004, 02:26 PM


    #3

    the char object in .NET has a function called IsNumber that returns true or false, it is great for looping through a string and looking at its contents, every string object in .NET has a Chars() array, which you can use this method from, Char is shared also so you can call the method like

    if char.IsNumber(«HELLO1»,5) then

    You can also use the IsNumeric as said above, but sometimes you need more precise checking that the IsNumeric function, for example IsNumeric will return true on a decial number, when perhaps you didnt want decimal numbers to be input.

    an example is this function I wrote that gets the numbers in a string, even if there are non numeric chars. I use it for when users have to enter numeric items like phone numbers because you cant tell what format they may use

    VB Code:

    1. Public Function GetNumbersInString(ByVal strText As String) As String

    2.         Dim strTemp As String

    3.         For i As Integer = 0 To strText.Length - 1

    4.             If Char.IsNumber(strText, i) Then

    5.                 strTemp += strText.Chars(i)

    6.             End If

    7.         Next

    8.         Return strTemp

    9.     End Function


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic .NET
  • Check if value is an integer in VBA


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Понравилась статья? Поделить с друзьями:
  • Excel vba if value is date
  • Excel vba if value is a number
  • Excel vba if then with or
  • Excel vba if then else and or
  • Excel vba if textbox1