Word vba is integer

I want to perform some task based on some ifs

my (uncomplete) code is

Sub checkif()
    Dim s
    With ActiveDocument.Range
        s = Val(ActiveDocument.Paragraphs.Count)
        s = s / 5
            If s = Integer then
                perform some task
            Else
                Exit Sub
            End If
     End With
End Sub

I am completely new to VBA and there are so many answers. I have tried several.
one is

Sub checkif2()
    Dim s
    With ActiveDocument.Range
        s = Val(ActiveDocument.Paragraphs.Count)
        s = s / 5
            If IsNumeric(s) Then
            MsgBox "is integer"
            Else
            MsgBox "not integer"
                Exit Sub
            End If
    End With
End Sub

This always give integer.

checked another one

Sub checkif2()
    Dim s
    With ActiveDocument.Range
        s = Val(ActiveDocument.Paragraphs.Count)
        s = s / 5
            If TypeName(s) = "Integer" Then
            MsgBox "is integer"
            Else
            MsgBox "not integer"
                Exit Sub
            End If
    End With
End Sub

Always give not integer.
Is there any method for Word VBA?

Ben Rhys-Lewis's user avatar

asked Dec 9, 2015 at 7:07

If s = Fix(s) is one way.

Fix strips off the fractional part.

Another approach in your case would be to check if the base 5 modulus is zero prior to taking the division. Use Mod for that: If s Mod 5 = 0.

answered Dec 9, 2015 at 7:22

Bathsheba's user avatar

BathshebaBathsheba

231k33 gold badges359 silver badges477 bronze badges

1

While trying Rahul’s answer, Found that This is simplest way.

If s = Int(s) Then

Tried for smaller file.
I will check with larger files and tell.

answered Dec 9, 2015 at 7:50

2

В языке 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

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

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

In this Article

  • Integer (Int) Variable Type
    • Long Variable Type
  • Decimal Values & Int Data Types
    • Decimal / Double Data Type
  • Declare Int Variable at Module or Global Level
    • Module Level
    • Global Level
  • Convert String to Int
  • Convert Int to String
    • Format Integer Stored as String

Integer (Int) Variable Type

The VBA Int data type is used to store whole numbers (no decimal values). However as we’ll see below, the Integer values must fall within the range ‑32768 to 32768.

To declare an Int variable, you use the Dim Statement (short for Dimension):

Dim intA as Integer

Then, to assign a value to a variable, simply use the equal sign:

intA = 30000

Putting this in a procedure looks like this:

Sub IntExample()
'declare the integer
   Dim intA as Integer
'populate the integer
   intA = 30000
'show the message box
   MsgBox intA
End Sub

If you run the code above, the following message box will be shown.

vba integer intexample msgbox

Long Variable Type

As mentioned above, Int variables can only store values between ‑32768 to 32768. If you attempt to assign a value outside that range to an Int variable you’ll receive an error:

vba integer intexample overflow error

When you click on de-bug, the code will break at the ‘populate the integer line as an integer cannot store a number as high as 50000.

vba integer intexample overflow debug

Instead, you can declare a variable with the Long data type:

Dim longA as Long

Long Variables can store very long data types (-2,147,483,648 to 2,147,483,648).

<<link to long variable article>>

Why would you use Int variables instead of Long variables?

Long variables use more memory. Years ago, memory was a big concern when writing code, however now computing technology is much improved and it’s doubtful you’ll encounter memory issues caused by long variables when writing VBA code.

We recommend always using Long variables instead of Int variables. We will continue this tutorial discussing Int variables, but keep in mind that you can use the Long variable type instead.

Decimal Values & Int Data Types

Int variables can not store decimal values. If you pass a decimal number an integer, the decimal number will be rounded to remove the decimal.

Therefore, if you were to run the procedure below:

Sub IntExampleB() 
'declare the integer
   Dim intA as Integer 
'populate the integer 
   intA = 3524.12
'show the message box 
   MsgBox intA 
End Sub

You would get the following result (rounding down):

vba integer passing decimal round down msgbox

However, this code below:

Sub IntExampleB()
 'declare the integer 
   Dim intA as Integer 
'populate the integer 
   intA = 3524.52 
'show the message box 
   MsgBox intA 
End Sub

Would return the following message box (rounding up):

vba integer passing decimal round up msgbox

Decimal / Double Data Type

If you want to store a decimal place, you would need to declare a variable that allows for decimal places.  There are 3 data types that you can use – Single, Double or Currency.

Dim sngPrice as Single
Dim dblPrice as Double
Dim curPrice as Currency

The Single data type will round the decimal point slightly differently to the double and currency data type, so it is preferable to use double to single for accuracy.  A double can have up to 12 decimal places while currency and single can both have up to 4 decimal places.

vba integer double example

For further information about these data types, you can have a look here.

Declare Int Variable at Module or Global Level

In the previous examples, we’ve declared the Int variable within a procedure. Variables declared with a procedure can only be used within that procedure.

vba integer procedure declaration

Instead, you can declare Int variables at the module or global level.

Module Level

Module level variables are declared at the top of code modules with the Dim statement.

vba integer module declaration

These variables can be used with any procedure in that code module.

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!

automacro

Learn More

Global Level

Global level variables are also declare at the top of code modules. However, instead of using the Dim statement, use the Public statement to indicate that the integer variable is available to be used throughout your VBA Project.

Public IntA as Integer

vba integer global declaration

If you were to declare the integer at a module level and then try to use it in a different module, an error would occur.

vba integer declaration notdefined

However, if you had used the Public keyword to declare the integer, the error would not occur and the procedure would run perfectly.

Convert String to Int

There might be an instance or instances when you will need to convert a number stored as a string to an integer value.

vba integer intexample string to integer immediate

You will notice in the immediate window that the integer value goes to the right indicating a number, while the string value goes to the left – indicating text.

Convert Int to String

Conversely, you can convert an integer value to a string.

vba integer intexample integer to string immediate

For further information about these data types, you can have a look here.

VBA Programming | Code Generator does work for you!

Format Integer Stored as String

<<also talk about the Format function, to assign number formatting>>

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

Validation

VBA provide rich collection of methods, functions can help user to build various own customized solutions. I am going to give some examples of VBA functions which developer usually looks for while developing programs.

VarType

This method provides datatype that a variable holds. VBA offers various constants to validate conditions like given below:

Constants

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

Checking a valid integer data type

Sub CheckDataType()
    If VarType(my_variable) = vbInteger Then
		MsgBox"Integer"
	Else
		MsgBox"Not Integer"
	End If
End Sub

Check valid Integer Value Method – 1

Public Function ValidateNumber(oValue As String) As Boolean
    If IsNumeric(oValue) Then
        ValidateNumber = True
    Else
        ValidateNumber = False
    End If
End Function

This method returns true/false based on value provided as input to the parameter oValue.

Using TypeName Method-2

Public Function GetDataType(oValue As String) As String
	Dim i As Integer 
	Dim j As Long

	i = 250
	j = 2500000

	If TypeName(i) = "Integer" Then
		GetDataType = "Variable ""i"" is an integer."
	Else
		GetDataType = "Variable ""i"" is a: " & TypeName(i)
	End If

	If TypeName(j) = "Integer" Then
		GetDataType = "Variable ""j"" is an integer."
	Else
		GetDataType = "Variable ""j"" is a: " & TypeName(j)
	End If
End Function

Email Address

Public Sub CheckValidEmail()
    Dim oEmail As String
    oEmail = InputBox("Enter Email Address : ", "E-Mail Address")
     ' Check email syntax
    If IsEmailValid(oEmail) Then
        MsgBox oEmail & " is a valid e-mail"
    Else
        MsgBox oEmail & " is not a valid e-mail"
    End If
End Sub
Public Function EmailValidateFunction(oEmailAddress As String) As Boolean
    Dim oStringArray As Variant
    Dim oItem As Variant
    Dim i As Long
    Dim c As String
    Dim isValdAddress As Boolean
    isValdAddress = True
    
	'identify position of @ in the string	
    i = Len(oEmailAddress) - Len(Application.Substitute(oEmailAddress, "@", ""))
    If i <> 1 Then 
		EmailValidateFunction = False
		Exit Function
	End If
    ReDim oStringArray(1 To 2)
    oStringArray(1) = Left(oEmailAddress, InStr(1, oEmailAddress, "@", 1) - 1)
    oStringArray(2) = Application.Substitute(Right(oEmailAddress, Len(oEmailAddress) - Len(oStringArray(1))), "@", "")
    For Each oItem In oStringArray
        If Len(oItem) <= 0 Then
            isValdAddress = False
            EmailValidateFunction = isValdAddress
            Exit Function
        End If
        For i = 1 To Len(oItem)
            c = LCase(Mid(oItem, i, 1))
            If InStr("abcdefghijklmnopqrstuvwxyz_-.", c) <= 0 And Not IsNumeric(c) Then
                isValdAddress = False
				'Return
                EmailValidateFunction = isValdAddress
                Exit Function
            End If
        Next i
        If Left(oItem, 1) = "." Or Right(oItem, 1) = "." Then
            isValdAddress = False
			'Return
            EmailValidateFunction = isValdAddress
            Exit Function
        End If
    Next oItem
    If InStr(oStringArray(2), ".") <= 0 Then
        isValdAddress = False
		'Return
        EmailValidateFunction = isValdAddress
        Exit Function
    End If
    i = Len(oStringArray(2)) - InStrRev(oStringArray(2), ".")
    If i <> 2 And i <> 3 Then
        isValdAddress = False
		'Return
        EmailValidateFunction = isValdAddress
        Exit Function
    End If
    If InStr(oEmailAddress, "..") > 0 Then
        isValdAddress = False
		'Return
        EmailValidateFunction = isValdAddress
        Exit Function
    End If
	'Return
    EmailValidateFunction = isValdAddress
End Function

Regular Expression

To validate a mail we can use another method which provides short code to achieve same goal mentioned in previous example. RegExp is a scripting library provided by Microsoft which we need to bring in our project by adding as reference as shown below:

Code example

Public Sub CheckEmail()
    Dim txtEmail As String
    txtEmail = InputBox("Enter Email Address:", "E-Mail Address")
     ' Check e-mail syntax
    If IsEmailValid(txtEmail) Then
        MsgBox txtEmail & " is a valid e-mail"
    Else
        MsgBox txtEmail & " is not a valid e-mail"
    End If
End Sub
Public Function IsEmailValid(ByVal strEmailAddress As String) As Boolean
    On Error GoTo Errh
    
    Dim objRegExp As New RegExp
    Dim blnIsValidEmail As Boolean
    
    objRegExp.IgnoreCase = True
    objRegExp.Global = True
    objRegExp.Pattern = "^([a-zA-Z0-9_-.]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$"
    
    blnIsValidEmail = objRegExp.Test(strEmailAddress)
    IsEmailValid = blnIsValidEmail
      
    Exit Function
    
Errh:
	If Err.Number <> 0 Then
    IsEmailValid = False
		MsgBox "Error#:  " & Err.Number & vbCrLf & vbCrLf & Err.Description
	End If
End Function

Null or Empty string

Public Function IsNullOrEmpty(oValue As String) As Boolean
    If IsEmpty(oValue) Then
        IsNullOrEmpty = True
    Else
        IsNullOrEmpty = False
    End If
End Function

Len Function

Public Function IsNullOrEmpty(oValue As String) As Boolean
    If Len(oValue)>0 Then
        IsNullOrEmpty = False
    Else
        IsNullOrEmpty = True
    End If
End Function

IsDate Function

Public Function IsValidDate(oDate As Date) As Boolean
    If IsDate(oDate) Then
        IsValidDate = True
    Else
        IsValidDate = False
    End If
End Function

Choose Function

Excel CHOOSE function returns a value from a list of values which should be a variant Parameter Array.

Syntax

=CHOOSE(Index As Single, ParamArray Choice() As Variant)

Code example

Function TestChoose() As String
    TestChoose = Choose(2, "Test", "Test1", "Test2")
End Function

Output

Test1

Asc() Function

Function Test(oChar As String) As String
    Test = Asc(oChar)
End Function

Output

65

Concatenate or &

Function Test(oVal1 As String, oVal2 As String) As String
    Test = oVal1 & oVal2
End Function

FORMAT() Function

This function is very useful function in VBA which holds the capability to perform various formatting on a string.

Sub CallingMethod()
	''Date Formatting in VBA
	Debug.Print "Full Date " & Format(Now, "DD-MMM-YYYY")
	Debug.Print "Date With Time " & Format(Now, "DD-MMM-YYYY: hh:mm:ss")
	Debug.Print "Short Day " & Format(Now, "DDD")
	Debug.Print "Long Day " & Format(Now, "DDDD")
	Debug.Print "Month Number " & Format(Now, "MM")
	Debug.Print "Short Month " & Format(Now, "MMM")
	Debug.Print "Long Month " & Format(Now, "MMMM")
	Debug.Print "Hours " & Format(Now, "HH")
End Sub

Output

Full Date 09-Dec-2017
Date With Time 09-Dec-2017: 18:35:40
Short Day Sat
Long Day Saturday
Month Number 12
Short Month Dec
Long Month December
Hours 18

There are many inbuilt functions listed below:

  • INSTR() : Returns the position of the first occurrence of a substring in a string.
  • INSTRREV() : Returns the position of the first occurrence of a string in another string, starting from the end of the string.
  • LCASE() : Converts string in Lower Case.
  • LEFT() : Returns a substring from a string, starting from the left-most character.
  • LEN() : Returns length of a string.
  • LTRIM() : Removes leading spaces from a string.
  • MID() : Extracts a substring from a string (starting at any position).
  • REPLACE() : Replaces a sequence of characters in a string with another set of characters.
  • RIGHT() : Extracts a substring from a string starting from the right-most character.
  • RTRIM() : Removes trailing spaces from a string.
  • SPACE() : Returns a string with a specified number of spaces.
  • SPLIT() : Used to split a string into substrings based on a delimiter.
  • STR() : Returns a string representation of a number.
  • STRCOMP() : Returns an integer value representing the result of a string comparison.
  • STRCONV() : Returns a string converted to uppercase, lowercase, proper case or Unicode.
  • STRREVERSE() : Returns a string whose characters are in reverse order.
  • TRIM() : Returns a text value with the leading and trailing spaces removed.
  • UCASE() : Converts string in Upper Case.
  • VAL() : Returns the numbers found in a string.
  • ISERROR(): Helps checking error.
  • ISNULL() : Helps getting Object State.
  • UBOUND() : Returns upper boundary of an Array.
  • LBOUND() : Returns lower boundary of an Array.

Next>> GetObject Vs. CreateObject VBA

  • 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

In this blog post we explain data types in VBA and provide detailed definitions for when they should be used.

Firstly a word on VBA variable names; a variable may be named anything you wish as long as it conforms to VBA’s naming rules. Variable names must start with a letter, may contain number characters or underscores ( _ ) but that’s it! Punctuation marks are not allowed. Also unlike other languages VBA is case-insensitive! This is important to understand and is demonstrated below.

Finally, there are some keywords that cannot be used as variable names.

Sub Declarations()
   Dim a as String	  	  ‘ a valid variable name
   Dim b_ as String		  ‘ a valid variable name
   Dim _b as String		  ‘ variable names must start with a letter
   Dim 2b as String		  ‘ variable names must start with a letter
   Dim c1 as String		  ‘ a valid variable name
   Dim d12 as String		  ‘ a valid variable name
   Dim e_e1 as String	  ‘ a valid variable name
   Dim f! as String		  ‘ punctuation not allowed in variable names
   Dim g as String		  ‘ a valid variable name
   Dim G as String		  ‘ an invalid variable name.  VBA is case-
				  ‘   insensitive, variables also cannot be
				  ‘   declared more than once in a code block
  Dim aVariableName as String	  ‘ a valid variable name
  Dim a_Variable_Name as String	  ‘ a valid variable name
  Dim HELLOWORLD as String	  ‘ a valid variable name

  Dim dim as String		  ‘ variable name is invalid as Dim is a keyword
End Sub

Boolean – (Yes/No)

A variable of type Boolean is the simplest possible data type available in VBA. It can only be set to 0 or -1. These are often thought of as states and correspond to Access’s Yes/No fields. In VBA you can assign a Boolean variable to True (-1) or False (0) or the numbers indicated in the brackets.
Notice we used capitalised words for True and False, which is because they are VBA keywords and you cannot name a variable a Keyword.

Sub trueOrFalse()
   Dim foo As Boolean
   Dim bar As Boolean
   foo = True      ' foo holds the value True
   bar = False     ' bar holds the value False
End Sub

Integer

At the beginning of the post we said that we have to tell the computer what type of data to expect before we can work on it. An Integer is another number data type, but its value must be between -32,768 and 32,767, and it must be a whole number, that is to say, it mustn’t contain decimal places. If you or your users try to save a decimal value (eg 2.5) to an integer variable, VBA will round the decimal value up or down to fit into an Integer data-type.

Sub IntegerDataType()
   Dim foo As Integer
   Dim bar As Integer
   Dim oof As Integer
   foo = 12345     ' foo is assigned the value 12,345
   bar = 2.5       ' bar is assigned the value 3 as VBA rounds it up
   bar = 2.4       ' bar is assigned the value 3 as VBA rounds it down
   foo = 32768     ' causes an overflow error as 32,768 is too big
End Sub

Long

Long is another number type and works just like Integer except it can hold a much larger range; Any number between -2,147,483,648 and +2,147,483,647.

Sub LongDataType()
   Dim foo As Long
   foo = 74345     ' foo is a variable assigned the value 74,345
End Sub

Single

Single is the smaller of the two “floating point” data types. Singles can represent any decimal number between -3.4028235E+38 through 1.401298E-45 for negative numbers and 1.401298E-45 through 3.4028235E+38 for positive numbers. Put more simply, the single data type has a decimal point in it.

Sub DoubleDataType()
   Dim foo As Single
   Dim bar As Single
   foo = 1.1       ' foo keeps the .1 decimal part
   bar = -20.2     ' bar also keep the decimal part
   foo = foo * bar ' foo equals -22.2200008392334
End Sub

Double

This is a “floating point” number as well and range in value from -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values and from 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values.

Sub DoubleDataType()
   Dim foo As Double
   Dim bar As Double
   foo = 1.1       ' foo keeps the .1 decimal part
   bar = -20.2     ' bar also keep the decimal part
   foo = foo * bar ' foo equals -22.2200008392334
End Sub

Currency

This data-type is a third “floating-point data” type in disguise. It’s a Single which has been engineered to represent behaviours typical of currencies. In particular it rounds off numbers to four decimal places. See the Figure below:

Sub CurrencyDataType()
   Dim bar As Single
   Dim foo As Currency
   bar = 1.1234567     ' this is the Single
   foo = bar           ' add the Single to the Currency
   MsgBox bar     ' bar contains 1.1234567
   MsgBox foo     ' foo contains 1.1235. Notice that the 4th digit
                   '   has been rounded up to 5
End Sub

Date

The Date data type is used to perform operations that involve dates AND times. In VBA there are several functions that operate on date variables which perform date and time calculations. It is important to know that date and time operations can be quite complicated and to help ease your burden you can use VBA’s DateTime object which encapsulates a lot of the difficulty of working with dates and time and can make them a little less of a headache to deal with. Date data types are the most complicated of all the data types to work with.

Here are a few operations we can do with date data types.

Sub DateDataTypes()
   Dim bar As Date
   Dim foo As Date
   bar = #11/15/1978#              ' bar set to this date but has no time
   foo = #12/10/2012 11:37:00 PM#  ' foo is set to this date and time
   bar = #1:00:09 AM#              ' bar is 1 hour and 9 seconds
   foo = #9:00:00 PM#              ' foo is 9PM
   foo = foo + bar                 ' foo is now 22:00:09
   MsgBox foo
   foo = foo - bar                 ' foo is back to 9PM
   MsgBox foo
End Sub

String

A String is any set of characters that are surrounded by double-quotation marks. For example “dog” is a String that contains three characters. Strings are very important to us as they can contain human language, and in fact contain almost any data we want, even numbers and punctuation marks. Strings are very versatile and you will use them extensively in your code. Often when you ask your users for information you will first store their input in a String before actually using the data provided; in this way Strings are often thought of as a safe data type.

Below are some Figures of Strings in action.

Sub StringDataTypes()
   Dim bar As String
   Dim foo As String
   Dim foobar As String

   bar = "Hello"                 ' bar now contains "Hello"
   foo = "world!"                ' foo contains "world!"
   foobar = bar & " " & foo      ' foobar now contains "Hello world!"
   ' notice that foobar has a +" "+ this means a SPACE character has been
   ' inserted into the String, without it foobar would contain "Helloworld!"

   foobar = bar + " " + foo      ' This Figure also shows that you can add
   ' Strings together (but you cannot subtract!)

   foo = "H" & "E" & "L" & "P"   ' foo now contains "HELP"
   bar = foo & foo               ' bar now contains "HELPHELP"
End Sub

Confusion

As stated above, when you collect input from a user you will usually collect it into a String. But be careful not to confuse String with Number data types. For example:

Sub Confusion()
   Dim bar, foo As String
   Dim foobar As String
 
   foo = "12.5"        ' user inputs "12.5"
   bar = "6.3"         ' user inputs "6.3"
   foobar = foo * bar  ' we multiple 12.5 and 6.3
   Debug.Print foobar  ' print the result - 0
                      ' It's ZERO!
  ' Remember foo and bar are STRING data types, 
  'so multiplying foo and bar as above is like 
  'saying "aaa" * "bbb" = 11  ? It doesn't make sense. 
  'But we collect data in a String because a String 
  'can accept all user input, even if they 12  put a 
  'punctuation mark in there.

  foo = "12.5.2"      ' user made a mistake
  bar = "ifvgj212m"   ' cat walks across the keyboard

  ' When collecting user input the data held in a String 
  'can be tested for accuracy and correctness before we 
  'load it into an Integer. If the user has not entered 
  'data correctly we ignore or display a useful message 
  'like "Error"...
End Sub

Variant

A variant is a special type which can contain any of the data types mentioned above (along with some others).

When a value is assigned to the variant data type the variable mutates into the type of the data assigned to it, and in some cases VBA can “detect” the type of data being passed and automatically assign a “correct” data type. This is useful for collecting data from users and also for writing procedures and functions for which you want to be able to call with a variable of any type.

Sub VariantDataType()
   Dim bar As Variant
   Dim foo As Variant
   Dim foobar As Variant
   bar = 1             ' bar is now an Integer
   foo = "oi!"         ' foo is now a String
   foobar = bar + 1.1  ' foobar is now a Double with the value of 2.1
   MsgBox TypeName(bar)    ' Integer
   MsgBox TypeName(foo)    ' String
  MsgBox TypeName(foobar) ' Double
End Sub

Related Posts

Variables Variables

Я хочу выполнить какую-то задачу, основанную на некоторых если

Мой (неполный) код

Sub checkif()
    Dim s
    With ActiveDocument.Range
        s = Val(ActiveDocument.Paragraphs.Count)
        s = s / 5
            If s = Integer then
                perform some task
            Else
                Exit Sub
            End If
     End With
End Sub

Я совершенно новичок в VBA, и есть так много ответов. Я пробовал несколько. один

Sub checkif2()
    Dim s
    With ActiveDocument.Range
        s = Val(ActiveDocument.Paragraphs.Count)
        s = s / 5
            If IsNumeric(s) Then
            MsgBox "is integer"
            Else
            MsgBox "not integer"
                Exit Sub
            End If
    End With
End Sub

Это всегда целое число.

Проверил еще один

Sub checkif2()
    Dim s
    With ActiveDocument.Range
        s = Val(ActiveDocument.Paragraphs.Count)
        s = s / 5
            If TypeName(s) = "Integer" Then
            MsgBox "is integer"
            Else
            MsgBox "not integer"
                Exit Sub
            End If
    End With
End Sub

Всегда указывайте не целое число. Есть ли какой-нибудь метод для Word VBA?

2 ответа

Лучший ответ

If s = Fix(s) — односторонний.

Fix удаляет дробную часть.

Другой подход в вашем случае — проверить, равен ли базовый 5 модуль нулю, прежде чем делать деление. Для этого используйте Mod: If s Mod 5 = 0.


1

Bathsheba
9 Дек 2015 в 08:38

Пробуя ответ Рахула, обнаружил, что это самый простой способ.

If s = Int(s) Then

Пробовал для меньшего файла. Я проверю с файлами большего размера и расскажу.


1

user5657754user5657754
9 Дек 2015 в 07:50

Like this post? Please share to your friends:
  • Word using prefix semi
  • Word vba if не равно
  • Word using prefix mis
  • Word vba if error
  • Word using prefix dis