What is the square root function in VBA excel? I tried SQRT() and Root() but none of them are working, my Excel version in 2013.
asked Apr 28, 2017 at 11:53
2
Use the oddly named
VBA.Sqr(n)
where n is your number for which you want the square root computed. The VBA. prefix is optional, but it helps descriminate between VBA and any other library you might have referenced.
answered Apr 28, 2017 at 11:55
BathshebaBathsheba
231k33 gold badges360 silver badges480 bronze badges
1
Nth root can be obtained with VBA with:
Option Explicit
Function NthRoot(dblNumber As Double, lngRoot As Long) As Double
NthRoot = dblNumber ^ (1 / lngRoot)
End Function
So for square root:
? NthRoot(64, 2)
8
? NthRoot(64.33333, 2)
8.02080606921773
answered Apr 28, 2017 at 13:15
Robin MackenzieRobin Mackenzie
18.3k7 gold badges38 silver badges54 bronze badges
You can use the ^ operator to obtain square roots. Just raise the number you started with to the power of 0.5:
81^0.5 will give you 9 and 256^0.5 will give you 16
answered Apr 28, 2017 at 23:23
barrowcbarrowc
10.4k1 gold badge40 silver badges53 bronze badges
Sqr : is the function used to calcualte the sqare root, or you can use ^0.5
Function getDistance(x1, y1, x2, y2)
getDistance = Sqr((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
End Function
answered Sep 10, 2022 at 2:26
Arpan SainiArpan Saini
4,4791 gold badge39 silver badges50 bronze badges
Permalink
Cannot retrieve contributors at this time
| title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
|---|---|---|---|---|---|---|
|
Sqr function (Visual Basic for Applications) |
vblr6.chm1009029 |
vblr6.chm1009029 |
office |
ce2add56-f943-9470-0caa-befda14d124a |
12/13/2018 |
medium |
Returns a Double specifying the square root of a number.
Syntax
Sqr(number)
The required number argument is a Double or any valid numeric expression greater than or equal to zero.
Example
This example uses the Sqr function to calculate the square root of a number.
Dim MySqr MySqr = Sqr(4) ' Returns 2. MySqr = Sqr(23) ' Returns 4.79583152331272. MySqr = Sqr(0) ' Returns 0. MySqr = Sqr(-4) ' Generates a run-time error.
See also
- Functions (Visual Basic for Applications)
[!includeSupport and feedback]
Excel VBA Square Root Function
In this article, we will see an outline on Excel VBA Square Root. Every time working on Excel, you must have used the SQRT function that gives the square root of any whole number as a result. Is it possible to capture the square root of a number under VBA? Well, the answer is a sure Yes! You can get the square root of any positive number through VBA using the VBA SQR function. This function is a built-in VBA function and can be used on any positive integer to get the square root of it. Well, this function is very similar to the one which we use as a spreadsheet function SQRT and also take the same single argument “Number” which should be positive. We can’t get the square roots of Imaginary numbers either and entering negative values is of no use because there is no possible way with which a negative square value of a number can be captured.
Syntax:
Syntax for VBA square root function is pretty simple and is look similar to the one of spreadsheet SQRT function.
Where Number is a sole argument that needs to be provided and should be strictly positive. Since we can’t have a negative square values of any number, chances of getting a negative square root value is impossible. Also, no scope for finding out the square roots of the complex numbers. This argument can be provided directly as a number or a variable assigned to the number or a spreadsheet cell reference where the number is stored. Also, the point to be noted here is, system by default considers the argument you provide as a double to give you the square root on any number irrespective of the fact that it is a whole square or not (Ex. 87, is not the whole square, but will still get the square root value since the number type is double. You can still define a number as an integer and then use it as an argument to SQR function. It will round to the closest square root value if the number provided is not a whole square.
How to Use Square Root Function in Excel VBA?
Below are the different examples to use the Square Root function in Excel VBA.
You can download this VBA Square Root Excel Template here – VBA Square Root Excel Template
VBA Square Root – Example #1
Follow the steps below to see how exactly the VBA SQR function works.
Step 1: Click on the Developer tab and then click the Visual Basic (ALT +F11) icon.
Step 2: Open Module from the Insert menu tab as shown below.
Step 3: Define a new sub-procedure that can hold the macro under the newly inserted module.
Code:
Sub sqrt_Example1() End Sub
Step 4: Use the assignment operator to assign the value of the VBA square root function to a variable named “sqr_root” so that we can print the result and see if it works fine.
Code:
Sub sqrt_Example1() sqr_root = Sqr(121) End Sub
Step 5: Use the MsgBox function so that we can print the result as a message box that will pop-up as soon as we run the code.
Code:
Sub sqrt_Example1() sqr_root = Sqr(121) MsgBox "Square Root of Given Number is: " & sqr_root End Sub
Step 6: Run this code by hitting F5 or Run button placed at the uppermost panel.
As soon as you run this code, you should see an output as shown below.
VBA Square Root – Example #2
Let’s dive deeper into the VBA SQR function and try to find out some different cases.
Step 1: Define sub-procedure that can hold your macros.
Code:
Sub sqrt_Example2() End Sub
Step 2: We need to define two new variables as integer. One for storing the value which we want a square root for. Another variable would be for storing the result of the square root after we apply the SQR function.
Code:
Sub sqrt_Example2() Dim square_num As Integer Dim square_root As Integer End Sub
Step 3: Assign value as 87 to the square_num variable using the assignment operator (‘=’). This is the number for which we wanted to capture the square root value.
Code:
Sub sqrt_Example2() Dim square_num As Integer Dim square_root As Integer square_num = 87 End Sub
Step 4: Use the SQR function and assignment operator to assign the value of the square root to the square_root variable. Use square_num as an argument under the SQR function (the number for which we wanted the square root value).
Code:
Sub sqrt_Example2() Dim square_num As Integer Dim square_root As Integer square_num = 87 square_root = Sqr(square_num) End Sub
Step 5: Use MsgBox Property to show the value of the square root as a message that pops up as soon as you run the code.
Code:
Sub sqrt_Example2() Dim square_num As Integer Dim square_root As Integer square_num = 87 square_root = Sqr(square_num) MsgBox "Square Root for Given Number is: " & square_root End Sub
Step 6: Run this code by hitting the F5 or Run button which is placed on the topmost ribbon of VBE.
Step 7: See the output in a message box as shown below:
However, this is not the actual square root value for number 87. This is the square root value for number 81. Why in the world VBA is giving wrong output for SQR function?
Well, there is nothing wrong with VBA. If something is wrong, it is ideal with our code.
Since we have defined the variables as integers, we are restricting the VBA to give the square roots of only those numbers which are whole square numbers (Ex. 4, 9, 16, 25, etc.). If any number is not a whole square, the VBA SQR function instead of throwing an error, it gives a square root value for a number that is close to the current number. Here, 87 has 81 as the closest whole square number. Therefore, you are getting the output as 9.
Step 8: Let’s see what happens when we tweak the code by defining the square_root variable as Double instead of Integer.
Code:
Sub sqrt_Example2() Dim square_num As Integer Dim square_root As Double square_num = 87 square_root = Sqr(square_num) MsgBox "Square Root for Given Number is: " & square_root End Sub
Step 9: You will see that the system now can capture the actual square root value for the number 87.
Things to Remember
- If you provide a negative number as an argument under the VBA SQR function, it will throw a Run-time error ‘5’. Since it is not possible to have a number with negative square values.
- If you have a negative number, make sure you are converting it to a positive entity with the help of the ABS function. You can also check if the number is positive or not with the help of the SGN function under VBA.
- If you put zero as an argument under the VBA SQR function, you will get the square root value as zero.
Recommended Articles
This is a guide to VBA Square Root. Here we discuss how to use Square Root Function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA IF Statements
- VBA Sort
- VBA While Loop
- VBA Counter
This Excel tutorial explains how to use the Excel SQR function with syntax and examples.
Description
The Microsoft Excel SQR function returns the square root of a number.
The SQR function is a built-in function in Excel that is categorized as a Math/Trig Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Syntax
The syntax for the SQR function in Microsoft Excel is:
Sqr( number )
Parameters or Arguments
- number
- A positive number that you wish to return the square root for.
Returns
The SQR function returns a numeric value.
If a negative number is entered in the number parameter, the SQR function will raise an error.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
The SQR function can only be used in VBA code in Microsoft Excel. If you need to calculate the square root within a worksheet formula, try the SQRT function.
Let’s look at some Excel SQR function examples and explore how to use the SQR function in Excel VBA code:
=Sqr(25) Result: 5 =Sqr(30) Result: 5.47722557505166 =Sqr(2.5) Result: 1.58113883008419
For example:
Dim LResult As Double LResult = Sqr(900) Msgbox LResult
In this example, the variable called LResult would now contain the value 30.
- Функция Excel VBA Square Root
Функция Excel VBA Square Root
В этой статье мы увидим схему Excel VBA Square Root. Каждый раз, работая в Excel, вы должны использовать функцию SQRT, которая дает квадратный корень любого целого числа в результате. Можно ли захватить квадратный корень из числа под VBA? Ну, ответ, конечно, да! Вы можете получить квадратный корень любого положительного числа через VBA, используя функцию VBA SQR. Эта функция является встроенной функцией VBA и может использоваться для любого положительного целого числа, чтобы получить ее квадратный корень. Ну, эта функция очень похожа на ту, которую мы используем в качестве функции электронной таблицы SQRT, а также принимаем тот же единственный аргумент «Число», который должен быть положительным. Мы также не можем получить квадратные корни мнимых чисел, и ввод отрицательных значений бесполезен, потому что нет никакого способа, которым можно получить отрицательное квадратное значение числа.
Синтаксис:
Синтаксис функции квадратного корня VBA довольно прост и похож на синтаксис функции SQRT электронной таблицы.
Где Number — это единственный аргумент, который необходимо указать и который должен быть строго положительным. Поскольку мы не можем иметь отрицательные квадратные значения любого числа, шансы получить отрицательное значение квадратного корня невозможны. Кроме того, нет возможности узнать квадратные корни комплексных чисел. Этот аргумент может быть предоставлен непосредственно в виде числа или переменной, назначенной номеру, или ссылки на ячейку электронной таблицы, где хранится число. Кроме того, следует отметить, что система по умолчанию считает аргумент, который вы задаете, двойным, чтобы получить квадратный корень для любого числа, независимо от того, является он целым квадратом или нет (пример 87 не является целый квадрат, но все равно получит значение квадратного корня, так как тип числа двойной. Вы все еще можете определить число как целое число, а затем использовать его в качестве аргумента функции SQR. Оно округляется до ближайшего значения квадратного корня, если число при условии, не полная площадь.
Как использовать функцию квадратного корня в Excel VBA?
Ниже приведены различные примеры использования функции квадратного корня в Excel VBA.
Вы можете скачать этот шаблон Excel с квадратным корнем VBA здесь — Шаблон Excel с квадратным корнем VBA
Квадратный корень VBA — Пример № 1
Выполните следующие действия, чтобы увидеть, как именно работает функция VBA SQR.
Шаг 1. Откройте вкладку « Разработчик » и щелкните значок Visual Basic (ALT + F11).
Шаг 2: Откройте модуль на вкладке меню «Вставка», как показано ниже.
Шаг 3: Определите новую подпроцедуру, которая может содержать макрос под вновь вставленным модулем.
Код:
Sub sqrt_Example1 () End Sub
Шаг 4: Используйте оператор присваивания, чтобы присвоить значение функции квадратного корня VBA переменной с именем « sqr_root », чтобы мы могли напечатать результат и посмотреть, работает ли он нормально.
Код:
Sub sqrt_Example1 () sqr_root = Sqr (121) End Sub
Шаг 5: Используйте функцию MsgBox, чтобы мы могли напечатать результат в виде окна сообщения, которое появится, как только мы запустим код.
Код:
Sub sqrt_Example1 () sqr_root = Sqr (121) MsgBox "Квадратный корень данного номера:" & sqr_root End Sub
Шаг 6: Запустите этот код, нажав F5 или кнопку Run, расположенную на самой верхней панели.
Как только вы запустите этот код, вы должны увидеть вывод, как показано ниже.
Квадратный корень VBA — Пример №2
Давайте углубимся в функцию SQR VBA и попытаемся выяснить несколько разных случаев.
Шаг 1: Определите подпроцедуру, которая может содержать ваши макросы.
Код:
Sub sqrt_Example2 () End Sub
Шаг 2: Нам нужно определить две новые переменные как целое число. Один для хранения значения, для которого мы хотим получить квадратный корень. Другая переменная будет для хранения результата квадратного корня после того, как мы применим функцию SQR.
Код:
Sub sqrt_Example2 () Dim square_num As Integer Dim square_root As Integer End Sub
Шаг 3: Присвойте значение как 87 переменной square_num, используя оператор присваивания (‘=’). Это число, для которого мы хотели получить значение квадратного корня.
Код:
Sub sqrt_Example2 () Dim square_num As Integer Dim square_root As Integer square_num = 87 End Sub
Шаг 4: Используйте функцию SQR и оператор присваивания, чтобы присвоить значение квадратного корня переменной square_root . Используйте square_num в качестве аргумента в функции SQR (число, для которого мы хотели получить значение квадратного корня).
Код:
Sub sqrt_Example2 () Dim square_num As Integer Dim square_root As Integer square_num = 87 square_root = Sqr (square_num) End Sub
Шаг 5: Используйте свойство MsgBox, чтобы показать значение квадратного корня в виде сообщения, которое появляется, как только вы запускаете код.
Код:
Sub sqrt_Example2 () Dim square_num As Integer Dim square_root As Integer square_num = 87 square_root = Sqr (square_num) MsgBox "Квадратный корень для заданного числа:" & square_root End Sub
Шаг 6: Запустите этот код, нажав кнопку F5 или Run, расположенную на самой верхней ленте VBE.
Шаг 7: Смотрите вывод в окне сообщения, как показано ниже:
Однако это не фактическое значение квадратного корня для числа 87. Это значение квадратного корня для числа 81. Почему в мире VBA дает неправильный вывод для функции SQR?
Ну, с VBA все в порядке. Если что-то не так, это идеально подходит для нашего кода.
Поскольку мы определили переменные как целые числа, мы ограничиваем VBA, чтобы давать квадратные корни только тех чисел, которые являются целыми квадратными числами (например, 4, 9, 16, 25 и т. Д.). Если какое-либо число не является целым квадратом, функция SQR VBA вместо выдачи ошибки выдает значение квадратного корня для числа, близкого к текущему числу. Здесь 87 имеет 81 как ближайшее целое квадратное число. Таким образом, вы получаете вывод как 9.
Шаг 8: Давайте посмотрим, что происходит, когда мы настраиваем код, определяя переменную square_root как Double вместо Integer.
Код:
Sub sqrt_Example2 () Dim square_num As Integer Dim square_root As Double square_num = 87 square_root = Sqr (square_num) MsgBox "Квадратный корень для заданного числа:" & square_root End Sub
Шаг 9: Вы увидите, что система теперь может зафиксировать фактическое значение квадратного корня для числа 87.
То, что нужно запомнить
- Если вы предоставите отрицательное число в качестве аргумента в функции SQR VBA, он выдаст ошибку времени выполнения «5» . Так как невозможно иметь число с отрицательными квадратными значениями.
- Если у вас есть отрицательное число, убедитесь, что вы преобразуете его в положительную сущность с помощью функции ABS. Вы также можете проверить, является ли число положительным или нет, с помощью функции SGN в VBA.
- Если вы установите ноль в качестве аргумента в функции VBA SQR, вы получите значение квадратного корня как ноль.
Рекомендуемые статьи
Это руководство по VBA Square Root. Здесь мы обсудим, как использовать функцию квадратного корня в Excel VBA вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —
- VBA IF Заявления | Шаблоны Excel
- Как использовать функцию сортировки Excel VBA?
- VBA While Loop (Примеры с шаблоном Excel)
- Что такое счетчик VBA (примеры)?


































