Функция cdbl vba excel

Функции преобразования типов данных в VBA Excel. Наименования функций, синтаксис, типы возвращаемых данных, диапазоны допустимых значений выражения-аргумента.

Синтаксис функций преобразования

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

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

Функции преобразования типов

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

Функция Тип данных Диапазон значений аргумента
CBool Boolean Любое допустимое строковое или числовое выражение.
CByte Byte От 0 до 255.
CCur Currency От -922 337 203 685 477,5808 до 922 337 203 685 477,5807.
CDate Date Любое допустимое выражение даты.
CDbl Double От -1,79769313486231E308 до -4,94065645841247E-324 для отрицательных значений; от 4,94065645841247E-324 до 1,79769313486232E308 для положительных значений.
CDec Decimal 79 228 162 514 264 337 593 543 950 335 для чисел без десятичных знаков. Для чисел с 28 десятичными знаками диапазон составляет 7,9228162514264337593543950335. Наименьшим возможным числом, отличным от нуля, является число 0,0000000000000000000000000001.
CInt Integer От -32 768 до 32 767, дробная часть округляется.
CLng Long От -2 147 483 648 до 2 147 483 647, дробная часть округляется.
CSng Single От -3,402823E38 до -1,401298E-45 для отрицательных значений; от 1,401298E-45 до 3,402823E38 для положительных значений.
CStr String Результат, возвращаемый функцией CStr, зависит от аргумента Выражение.
CVar Variant Диапазон совпадает с типом Double  для числовых значений и с типом  String  для нечисловых значений.

Дополнительно для VBA7:

Функция Тип данных Диапазон значений аргумента
CLngLng LongLong От -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807, дробная часть округляется. Действительно только для 64-разрядных платформ.
CLngPtr LongPtr От -2 147 483 648 до 2 147 483 647 для 32-разрядных платформ, от -9 223 372 036 854 775 808 до 9 223 372 036 854 775 807 для 64-разрядных платформ, дробная часть округляется в обоих типах систем.

Примеры преобразования типов

Функция CBool

Функция CBool используется для преобразования выражений в тип данных Boolean.

Dim a

a = CBool(10) ‘Результат: True

a = CBool(0) ‘Результат: False

a = CBool(«True») ‘Результат: True

a = CBool(«Test») ‘Результат: Error

Dim a, b, c

a = «Test1»

b = «Test2»

c = CBool(a = b) ‘Результат: False

c = CBool(a <> b) ‘Результат: True

Функция CByte

Функция CByte используется для преобразования выражений в тип данных Byte.

Dim a, b, c

a = 654

b = 3.36

c = a / b ‘Результат: 194,642857142857

c = CByte(c) ‘Результат: 195

c = a * b ‘Результат: 2197,44

c = CByte(c) ‘Результат: Error

Функция CCur

Функция CCur используется для преобразования выражений в тип данных Currency.

Dim a, b, c

a = 254.6598254

b = 569.2156843

c = a + b ‘Результат: 823,8755097

c = CCur(a + b) ‘Результат: 823,8755

Функция CDate

Функция CDate используется для преобразования выражений в тип данных Date. Она распознает форматы даты в соответствии с национальной настройкой системы.

Dim a As String, b As Date, c As Double

a = «28.01.2021»

b = CDate(a) ‘Результат: #28.01.2021#

c = CDbl(b) ‘Результат: 44224

Dim a

a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05#

a = CDate(44298) ‘Результат: #12.04.2021#

a = CDate(0.63895) ‘Результат: #15:20:05#

Функция CDbl

Функция CDbl используется для преобразования выражений в тип данных Double.

Dim a As String, b As String, c As Double

a = «45,3695423»

b = «548955,756»

c = CDbl(a) + CDbl(b) ‘Результат: 549001,1255423

Примечание
Eсли основной язык системы – русский, при записи в редакторе VBA Excel дробного числа в виде текста, ставим в качестве разделителя десятичных разрядов – запятую. Проверьте разделитель по умолчанию для своей национальной системы:
MsgBox Application.DecimalSeparator

Функция CDec

Функция CDec используется для преобразования выражений в тип данных Decimal.

Dim a As String, b As Double, c

a = «5,9228162514264337593543950335»

b = 5.92281625142643

c = CDec(a) CDec(b) ‘Результат: 0,0000000000000037593543950335

Dim a As Double, b As String, c

a = 4.2643E14

b = CStr(a) ‘Результат: «4,2643E-14»

c = CDec(a) ‘Результат: 0,000000000000042643

Функция CInt

Функция CInt используется для преобразования выражений в тип данных Integer.

Dim a As String, b As Integer

a = «2355,9228»

b = CInt(a) ‘Результат: 2356

Функция CLng

Функция CLng используется для преобразования выражений в тип данных Long.

Dim a As Date, b As Long

a = CDate(44298.63895) ‘Результат: #12.04.2021 15:20:05#

b = CLng(a) ‘Результат: 44299

a = CDate(b) ‘Результат: #13.04.2021#

Функция CSng

Функция CSng используется для преобразования выражений в тип данных Single.

Dim a As String, b As Single

a = «3,2365625106»

b = CSng(a) ‘Результат: 3,236562

Функция CStr

Функция CStr используется для преобразования выражений в тип данных String.

Dim a As Single, b As String

a = 5106.23

b = CStr(a) ‘Результат: «5106,23»

Функция CVar

Функция CVar используется для преобразования выражений в тип данных Variant.

Dim a As Double, b As String, c

a = 549258.232546

b = «Новое сообщение»

c = CVar(a) ‘Результат: 549258,232546 (Variant/Double)

c = CVar(b) ‘Результат: «Новое сообщение» (Variant/String)

Функции преобразования типов данных используются в тексте процедур VBA Excel для того, чтобы указать, что результатом выполнения той или иной операции должны стать данные определенного типа, отличающегося от типа, заданного по умолчанию.


CDbl

CDbl(Expression)

Функция CDbl(Conversion to Doble) преобразует выражение в тип данных двойной точности Double

Параметры

Expression
Обязательный аргумент представляет собой любое числовое выражение или строку, представляющую число в диапазоне значений от -1.79769313486232E308 до -4.94065645841247E-324 для отрицательных значений, и от 4.94065645841247E-324 до 1.79769313486232E308 для положительных значений
Если Expression не попадает в диапазон допустимых значений Double, генерируется ошибка стадии выполнения Overflow

Если Expression имеет тип данных String, он должен представлять число, иначе генерируется ошибка стадии выполнения Type mismatch

Пример

Dim A, retval
A=CCur(123.4567) ' устанавливаем тип Currency
' Преобразуем результат в значение типа Double
retval=CDbl(A*1.7)
Debug.Print retval

Категория
Функции преобразования типа данных

VBA CDBL

What is Excel VBA CDBL?

CDBL is a VBA function that uses to convert the expressions into a double data type. VBA consists of a number of data conversion functions. This help to change the data type of a variable or value from one to another. In different calculations, the conversion is a necessary process to get the proper result. CDBL is one of the data conversion function included in the Type conversion functions in VBA. CDBL stands for ‘Convert to double’. While processing data you may come across situations to change the integer numbers to double. To print the accurate result this function will help you. VBA CDBL function only accepts numbers. Any expression apart from numbers will produce a type mismatch error.

Format of CDBL function in Excel VBA

CDBL is a simple function which requires a single expression to operate in VBA. The expression should be a number.

Syntax of CDBL

  • Expression: Is the number you want to convert into a floating number.

If the expression is anything apart from a number, the function will return a mismatch error. See the below example, where a non-number expression is passed to the function CDBL and it produced an error type mismatch.

CDBL 1

Use of CDBL Function in VBA

Let’s check how the VBA CDBL function helps us on data processing. To get a clear view and understand the practical use of changing the data type see the below example. You can see the difference according to the data type used on the same variable.

  • Declare a variable as integer data type and assign a floating value to it. While printing the value see how it’s going to show the value.

Code:

Private Sub addconvert()

Dim b As Integer

End Sub

VBA CDBL Example 1-1

  • A floating value is assigned to the declared integer variable. 785.456923785475 is assigned to variable b which is an integer variable.

Code:

Private Sub addconvert()

Dim b As Integer
b = 785.456923785475

End Sub

VBA CDBL Example 1-2

  • Using a message box, print the assigned value.

Code:

Private Sub addconvert()

Dim b As Integer
b = 785.456923785475
MsgBox b

End Sub

VBA CDBL Example 1-3

See how the results show difference while printing the value.

Result of Example 1-4

You have assigned a number with floating values but the output shows only the integer part of the given number. Here the variable ‘b’ is declared as integer number so it will not accept a floating value. The integer part of the decimal value is taken and the decimal part is avoided. Since the variable is declared as an integer the number will be rounded to the nearest integer.

To print the data as it is, changing the variable data type into double Instead of the integer data type.

  • By making a simple change in the same code you can print the given number as it is. Declare the variable as a double datatype.

Code:

Private Sub addconvert()

Dim b As Double

End Sub

VBA CDBL Example 1-5

  • A number as double is assigned to the declared double variable. 785.456923785475 is assigned to variable b which is double in datatype.

Code:

Private Sub addconvert()

Dim b As Double
b = 785.456923785475

End Sub

VBA CDBL Example 1-6

  • Using a message box print the assigned value.

Code:

Private Sub addconvert()

Dim b As Double
b = 785.456923785475
MsgBox b

End Sub

VBA CDBL Example 1-7

See how the results show difference while printing the value. You have assigned a number with floating values.

Result of Example 1-8

Compare both outputs you can see the difference. Even the data and variable are the same the change in data type changed the entire output. From this, you will get the importance of datatype and how it influences the entire program. This is the reason for using a different type of conversion functions with VBA.

Examples of CDBL Function in Excel VBA

Below are the different examples of VBA convert to double.

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

Example #1: Convert string data type to double

Let’s see how the data conversion is performing, and what are the changes that you can make with the help of data conversion functions. The string is a datatype which accepts all datatypes. A variable is defined as a string and assigns a number to it.

  • Use a private function to check the changes in different datatype, create a function convert as private the declare the variable ‘a’ as a string.

Code:

Private Sub convert()

Dim a As String

End Sub

VBA CDBL Example 2-1

  • To perform the conversion, you need a variable. Since the variable is converting into double data type declare it as a double datatype. After data conversion, the value will be assigned to this variable.

Code:

Private Sub convert()

Dim a As String
Dim convert As Double

End Sub

VBA CDBL Example 2-2

  • Assign a floating number 1234.5645879 to the string variable. The string datatype will accept the numbers with floating values.

Code:

Private Sub convert()

Dim a As String
Dim convert As Double
a = 1234.5645879

End Sub

VBA CDBL Example 2-3

  • Now use the VBA CDBL function to convert the value to double. You can use the ‘convert’ variable which is declared as a double datatype. Pass the variable ‘a’ as an expression to CDBL function.

Code:

Private Sub convert()

Dim a As String
Dim convert As Double
a = 1234.5645879
convert = CDbl(a)

End Sub

VBA CDBL Example 2-4

  • To view the output value, you can print using a message box.

Code:

Private Sub convert()

Dim a As String
Dim convert As Double
a = 1234.5645879
convert = CDbl(a)
MsgBox convert

End Sub

VBA CDBL Example 2-5

  • Run this code by hitting F5 directly or manually hitting the Run button on the upper left panel.

VBA CDBL Example 2-6

  • The value assigned to variable ‘a’ will be printed as same with floating points and an integer value. The value is converted into double data type and the same is printed as below.

Example #2 – Converting and Adding Two Numbers

You have two variables to add and find the sum as part of your calculation. Both are floating numbers with decimal values. But one variable is declared as integer and another as double.

  • Create a function add to find the sum of two numbers. Two variables A1 and A2 are declared as integer and double respectively.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double

End Sub

Example 3-1

  • Assign the two numbers to the respective variables. Both are two floating numbers with decimal values.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double
A1 = 1256.45
A2 = 1234.58

End Sub

Example 3-2

  • Declare a third variable sum as double data type since the result will be a double value.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double
Dim sum As Double
A1 = 1256.45
A2 = 1234.58

End Sub

VBA CDBL Example 3-3

  • Add the given two numbers and put the result in the variable sum.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double
Dim sum As Double
A1 = 1256.45
A2 = 1234.58
sum = A1 + A2

End Sub

Example 3-4

  • Using a message box lets print the output.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double
Dim sum As Double
A1 = 1256.45
A2 = 1234.58
sum = A1 + A2
MsgBox sum

End Sub

VBA CDBL Example 3-5

  • Run this code by hitting F5 directly or manually hitting the Run button on the upper left panel.

Result of Example 3-6

The expected result is 2491.03 and while checking the output you can see some difference in the result. The mismatch in result occurred due to the value taken by variable A1. Since this is an integer variable this will not accept the decimal part of the number only the integer part is taken while processing the sum.

  • To avoid this, convert the number A1 to double and assign the converted number to another variable A3.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double
Dim sum As Double
A1 = 1256.45
A2 = 1234.58
A3 = CDbl(1256.45)
sum = A1 + A2
MsgBox sum

End Sub

VBA CDBL Example 3-7

  • Now add the converted variable with A2 instead of A1. Since the number is converted to double datatype the value with floating numbers will be accepted and added with A2.

Code:

Private Sub add()

Dim A1 As Integer
Dim A2 As Double
Dim sum As Double
A1 = 1256.45
A2 = 1234.58
A3 = CDbl(1256.45)
sum = A2 + A3
MsgBox sum

End Sub

VBA CDBL Example 3-8

  • Run this code by hitting F5 directly or manually hitting the Run button on the upper left panel.

Result of Example 3-9

The sum value has been corrected and produced the expected result.

Things to Remember

  • VBA CDBL function will not accept values rather than a number.
  • A type mismatch error will be produced if a text value is given to the VBA CDBL function.
  • Double data type displays a 13 digit decimal values.
  • VBA CDBL function helps you to get a proper result while processing the numbers in Excel.

Recommended Articles

This is a guide to VBA CDBL Function. Here we discuss how to use VBA CDBL function to convert the value to Double data type in Excel along with some practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Block Comment
  2. VBA Named Range
  3. VBA Type Mismatch
  4. VBA RGB

VBA CDBL is an inbuilt data type conversion function. The use of this function is that it converts the data type of any given variable’s value into a Double data type. This function only takes a single argument: the variable’s value.

In VBA, “CDBL” stands for “Convert to Double.” This function converts the given number to a Double data type. Take a look at the syntax of the CDBL function.

CDBL Snytax

  • The expression is the value we are trying to convert to a Double data type.

We can convert any floating number stored as other than the Double data type by applying the CDBL function.

Point to Remember Here: We can convert only numerical values to Double data type. So, we cannot convert anything other than numerical value to double type, so we show “Type Mismatch Error in VBAWhen we assign a value to a variable that is not of its data type, we get Type mismatch Error or Error code 13. For example, if we assign a decimal or long value to an integer data type variable, we will get this error (Error Code 13) when we run the code.read more” like the below.

Type mismatch error

Table of contents
  • Excel VBA CDBL Function
    • Have you ever used a double data type in VBA coding?
    • Examples to Use VBA CDBL Function
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles

Have you ever used a double data type in VBA coding?

If not, it is worth having a look at it now. “Double” is the data type used to store the decimal position of the number. We can have up to 13 floating decimal numbers.

For example, look at the below VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Double Example 1

In the above, we have defined the variable (k) type as “Integer.” Dim k As Integer

Next, we have assigned the value as k = 25.4561248694615.

When we run the code, we will get the result as follows.

Double Example 1-1

We got the result as 25 since we have defined the variable as Integer VBA roundRound function in VBA is a mathematical function that rounds up or down the given number to the specific set of decimal places specified by the user to ease calculation.read more to the nearest integer value.

We need to change the variable type from Integer to Double to show the result.

Double Example 1-2

It should give us the exact number we assigned to the variable.

Double Example 1-3

Keeping this in mind, we can also convert all the fraction numbers stored as a non-double data type.

Examples to Use VBA CDBL Function

You can download this VBA CDBL Function Template here – VBA CDBL Function Template

Example #1

To start the proceedings, let’s look at the code below.

Code:

Sub Double_Example1()

    Dim k As String

    k = 48.14869569

    MsgBox k

End Sub

VBA CBDL Example 1

Now, we will run the code and see what happens.

VBA CBDL Example 1-2

Even though the VBA variable type is “String,” it still shows the decimal values because String can be of any data type, decimal or floating numbers shown as it is.

Now, we will change the vba data type from string to IntegerThe «CINT» function in VBA can be used to convert string data type variables to integer data types. It is a built-in function known as the data type conversion function that can be used as macro code.read more.

Code:

Sub Double_Example1()

    Dim k As Integer

    k = 48.14869569

    MsgBox k

End Sub

VBA CBDL Example 1-2

Now, we will run the code and see what happens.

VBA CBDL Example 1-3

It is where the CDBL function plays a vital role in converting the Integer data type to Double. So, the below code is the same for you.

Code:

Sub Double_Example1()

    Dim IntegerNumber As String
    Dim DoubleNumber As Double

    IntegerNumber = 48.14869569

    DoubleNumber = CDbl(IntegerNumber)

    MsgBox DoubleNumber

End Sub

VBA CBDL Example 1-4

It will convert the String data type value to Double.

excel vba cdbl Example 1-5

Example #2

Now, let’s convert the number 854.6947, stored as a Variant, to a Double data type.

Code:

Sub Double_Example2()

    Dim VaraintNumber
    Dim DoubleNumber As Double

    VaraintNumber = 854.6947

    DoubleNumber = CDbl(VaraintNumber)

    MsgBox DoubleNumber

End Sub

excel vba cdbl Example 2

The first variable we have declared as “Variant.” Dim VaraintNumber.

Note: When the variable type is not declared, it becomes a universal data type Variant.

Next, we have declared one more variable, i.e., Dim DoubleNumber As Double.

For the first variable, VaraintNumber, we have assigned the value as 854.6947.

Using the second variable, we have applied the CDBL function to convert the Variant value to a Double data type.

DoubleNumber = CDbl(VaraintNumber)

The final part is to show the result in the message box. MsgBox DoubleNumber

Now, we will run the code to see the result.

excel vba cdbl Example 2-1

Things to Remember

  • A Double data type can accept only numerical numbers.
  • If we supply the text value, it will cause an error of “Type Mismatch.”
  • A Double data type can display only 13 digits of floating numbers.

Recommended Articles

This article has been a guide to VBA CDBL. Here, we learn how to use the VBA CDBL function to convert the value to Double data type, along with some simple to advanced examples. Below are some useful Excel articles related to VBA: –

  • How to Declare VBA Global Variables?
  • VBA Data Type
  • Transpose in VBA
  • VBA Switch Function

Return to VBA Code Examples

In this Article

  • CDbl Function
    • VBA CDbl Convert Expression to Integer
    • VBA CDbl Converting String to Double
    • VBA CDbl Run-Time Error 13 Type Mismatch
    • VBA CDbl Regional Settings
    • VBA CDbl Converting Booleans to Doubles
    • VBA CDbl Converting Dates to Doubles

This tutorial will demonstrate how to use the CDbl VBA function to convert expressions to double data type.

CDbl Function

VBA CDbl Convert Expression to Integer

The VBA CDbl function can be used to convert expressions to double data type inside VBA code.

Sub CDblExample_1()
MsgBox CDbl(12.345)     'Result is: 12.345
MsgBox CDbl(-124)       'Result is: -124
MsgBox CDbl(0.000034)   'Result is: 0.000034
MsgBox CDbl(-12.000034) 'Result is: -12.000034
End Sub

VBA CDbl Converting String to Double

The VBA CDbl function can be used to convert strings to doubles if the characters in the string have a meaning as numbers.

Sub CDblExample_2()
Dim StrEx As String
StrEx = "112"
MsgBox CDbl(StrEx)
'Result is: 112

StrEx = "0.0003"
MsgBox CDbl(StrEx)
'Result is: 0.0003

StrEx = "11,00002"
MsgBox CDbl(StrEx)
'Result is: 1100002   , is ignored

StrEx = "$112"
MsgBox CDbl(StrEx)
'Result is: 112        $ is ignored
End Sub

VBA CDbl Run-Time Error 13 Type Mismatch

Using VBA CDbl function with strings that contain non-numerical characters or characters that don’t have meaning in numerical context will result in a Run-Time error ’13’: Type mismatch.

Sub CDblExample_3()
'The code below will result in an ERROR message
'CDbl cant handle non numerical characters
Dim StrEx As String
StrEx = "Ab13"
MsgBox CDbl(StrEx)
End Sub

VBA CDbl Regional Settings

VBA CDbl function has different behavior converting strings with comma or dot.  It uses the Regional Settings of the operating system for decimal separator and digit separator.

Sub CDblExample_4()
Dim StrEx As String
StrEx = "1,9"
MsgBox CDbl(StrEx)
'If Regional settings have , as a grouping separator then
'Result is: 19
'If Regional settings have , as a decimal separator then
'Result is: 1,9

StrEx = "1.9"
MsgBox CDbl(StrEx)
'If Regional settings have . as a grouping separator then
'Result is: 19
'If Regional settings have . as a decimal separator then
'Result is: 1.9
End Sub

VBA CDbl Converting Booleans to Doubles

VBA CDbl function can convert boolean variables to doubles. If the evaluated expression is true the resulting double is -1 and if the evaluated expression is false the resulting double is 0.

Sub CDblExample_5()
Dim BoolEx As Boolean
BoolEx = True
MsgBox CDbl(BoolEx)  'Result is: -1
MsgBox CDbl(2 = 2)   'Result is: -1

BoolEx = False
MsgBox CDbl(BoolEx)  'Result is: 0
MsgBox CDbl(1 = 2)   'Result is: 0
End Sub

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

VBA CDbl Converting Dates to Doubles

VBA CDbl function can convert a date variable to an integer. The returned value is the internal number used by excel for date storage rounded.

Sub CDblExample_6()
Dim DateEx As Date
DateEx = #2/3/1940#
MsgBox CDbl(DateEx)
'Result is: 14644
DateEx = #8/7/1964 10:41:00 PM#
MsgBox CDbl(DateEx)
'Result is: 23596.9451388889
DateEx = #3/7/1934 11:32:04 AM#
MsgBox CDbl(DateEx)
'Result is: 12485.4806018519
End Sub

Понравилась статья? Поделить с друзьями:
  • Функциональные возможности программы excel
  • Функция calculation в excel
  • Функциональные возможности word 2016
  • Функция cagr в excel
  • Функциональные возможности microsoft office word