Функция cos в vba excel

Access для Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 Еще…Меньше

Возвращает значение типа Double, указывающее косинус угла.

Синтаксис

Cos(

number

)

Требуемая аргумент является double или любым допустимым числовое выражение, который выражает угол в радианах.

Замечания

Функция Cos принимает угол и возвращает соотношение двух сторон правого треугольника. Отношение — это длина стороны, смежной с углом, деления на длину гипотезы.

Результат находится в диапазоне от -1 до 1.

Чтобы преобразовать градусы в радианы, умножьте градусы на число «пи» /180. Чтобы преобразовать радианы в градусы, умножьте значение в радианах на 180/Пи.

Пример запроса


Выражение


Результаты:

SELECT Cos(90) AS Cosine FROM ProductSales GROUP BY Cos(90);

Возвращает «косинус» аргумента-числа (любое числическое выражение, которое выражает угол в радианах) и возвращает его в столбце «Косинус».

Пример VBA

Примечание: В примерах ниже показано, как использовать эту функцию в модуле Visual Basic для приложений (VBA). Чтобы получить дополнительные сведения о работе с VBA, выберите Справочник разработчика в раскрывающемся списке рядом с полем Поиск и введите одно или несколько слов в поле поиска.

В этом примере функция Cos используется для возвращения косинуса угла.

Dim MyAngle, MySecant
MyAngle = 1.3 ' Define angle in radians.
MySecant = 1 / Cos(MyAngle) ' Calculate secant.

Нужна дополнительная помощь?

Home / VBA / Top VBA Functions / VBA COS Function (Syntax + Example)

The VBA COS function is listed under the math category of VBA functions. When you use it in a VBA code, it returns the cosine of a supplied angle. In simple words, a cosine of an angle is the length of the adjacent side of a right triangle, divided by the length of the hypotenuse which this function returns.

Cos(Number)

Arguments

  • Number: The angle value for which you want to calculate the cosine.

Example

To practically understand how to use VBA COS function, you need to go through the below example where we have written a vba code by using it:

Sub example_COS()
Range("B1").Value = Cos(Range("A1"))
End Sub

In the above example, we have used the value from cell A1 (12) and then we have used the COS function to get the cosine of a supplied angle and it has returned 0.843853958732492 in the result.

Notes

  • If the value specified is a value other than a number or a string which can’t be recognized as a number, VBA will return the run-time 13 error.
  • You can multiply the result returned by the COS with pi/180 to convert it into radians and 180/pi to convert it into degrees.

VBA Cos function in Excel is categorized as Math(Mathematical) & Trig function. This is a built-in Excel and VBA Function. This function returns the cosine value of an angle of number in radians. The returned cosine value is between -1 and 1.

  • Convert degrees to radians, multiply degrees with pi/180.
  • To convert radians to degrees, multiply radians with 180/pi.

We can use this function in VBA and Excel. This function can be used in either procedure or function in a VBA editor window in Excel. This VBA Cos Function in any number of times in any number of procedures or functions. Let us learn what is the syntax and parameters of the Cos function, where we can use this Cos Function and real-time examples in Excel VBA.

Table of Contents:

  • Overview
  • Syntax of VBA Cos Function
  • Parameters or Arguments
  • Where we can apply or use VBA Cos Function?
  • Example 1: Find the Cosine value(0)
  • Example 2: Find the Cosine value(60)
  • Example 3: Find the Cosine value(270)
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the Cos Function in VBA is

Cos(Number)

The Cos function returns value is a Double data type.

Parameters or Arguments:

The Cos function has one argument in Excel VBA.
where
Number:The Number is a required parameter. It represents an angle in radians, which we want to find cosine value.

Where we can apply or use VBA Cos Function?

We can use this Cos Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Find the Cosine value(0)

Here is a simple example of the VBA Abs function. This below example returns the cosine value(0) of a number.

'Find the Cosine value(0)
Sub VBA_Cos_Function_Ex1()

    'Variable declaration
    Dim iValue As Integer
    Dim dResult As Double
    
    iValue = 0
        
    dResult = Cos(iValue)
        
    MsgBox "The Cosine value of 0 is : "  & dResult, vbInformation, "VBA Cos Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA Cos Function

Example 2: Find the Cosine value(60)

Here is a simple example of the VBA Abs function. This below example returns the cosine value(60) of a number.

'Find the Cosine value(60)
Sub VBA_Cos_Function_Ex2()

    'Variable declaration
    Dim iValue As Integer
    Dim dResult As Double
    
    iValue = 60
        
    dResult = Cos(iValue)
        
    MsgBox "The Cosine value of 60 is : " & vbCrLf & dResult , vbInformation, "VBA Cos Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA Cos Function

Example 3: Find the Cosine value(270)

Here is a simple example of the VBA Abs function. This below example returns the cosine value(270) of a number.

'Find the Cosine value(270)
Sub VBA_Cos_Function_Ex3()

    'Variable declaration
    Dim iValue As Integer
    Dim dResult As Double
    
    iValue = 270
        
    dResult = Cos(iValue)
        
    MsgBox "The Cosine value of 270 is : " & vbCrLf & dResult , vbInformation, "VBA Cos Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA Cos Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

totn Excel Functions


This Excel tutorial explains how to use the Excel COS function with syntax and examples.

Description

The Microsoft Excel COS function returns the cosine of an angle.

The COS function is a built-in function in Excel that is categorized as a Math/Trig Function. It can be used as a worksheet function (WS) and a VBA function (VBA) in Excel. As a worksheet function, the COS function can be entered as part of a formula in a cell of a worksheet. 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 COS function in Microsoft Excel is:

COS( number )

Parameters or Arguments

number
A numeric value used to calculate the cosine.

Returns

The COS function returns a numeric value.

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

  • Worksheet function (WS)
  • VBA function (VBA)

Example (as Worksheet Function)

Let’s look at some Excel COS function examples and explore how to use the COS function as a worksheet function in Microsoft Excel:

Microsoft Excel

Based on the Excel spreadsheet above, the following COS examples would return:

=COS(A1)
Result: 0.980066578

=COS(A2)
Result: 0.939372713

=COS(A3)
Result: -0.999964658

=COS(200)
Result: 0.487187675

Example (as VBA Function)

The COS function can also be used in VBA code in Microsoft Excel.

Let’s look at some Excel COS function examples and explore how to use the COS function in Excel VBA code:

Dim LNumber As Double

LNumber = Cos(210)

In this example, the variable called LNumber would now contain the value of -0.883877473.

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

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

ABS(num) – Функция возвращает значение числа по модулю.

Exp(num) – Функция позволяет получить значение экспоненты, передаваемый параметр (максимальное значение ровно 709 782712893) является степенью, в которую нужно возвести экспоненту. Соответственно, если параметр равен 1, то мы получить чистое значение экспоненты.

Fix(num) – Функция возвращает целую часть от переданного дробного значения. Если переданное значение является отрицательным, то возвращается ближайшее отрицательное целое число, большее, либо равное указанному.

Int(num) – Математическая функция vba возвращает целую часть от переданного дробного значения. Если переданное значение является отрицательным, то возвращается ближайшее отрицательное целое число, меньшее, либо равное указанному.

Rnd(random) – Функция вернет число, входящее в диапазон от 0 до 1 в случайном порядке, при этом, само число 1 не входит в диапазон, а 0 – входит. Перед вызовом функции надо прописывать конструкцию Randomize, которая отвечает за включение генератора случайных чисел.

В зависимости от значения переданного параметра random, данная математическая функция vba работает следующим образом:

  • Параметр отсутствует или больше 0 — Генерация следующего случайного числа в последовательности. Повторный запуск программы генерирует аналогичную последовательность.
  • Параметр меньше 0 – Происходит генерация одного и того же числа, опираясь на переданный аргумент.
  • Параметр равен 0 — Происходит генерация одного и того же числа, опираясь на число из предыдущего вызова.

Round(num, [accr])  — Округление заданного числа (num) до заданной точности (accr).

Sgn(num) – Данная математическая функция vba позволяет узнать знак числа, переданного как аргумент. Функция vba вернет следующие значения:

  • 0 – Число равно 0
  • -1 – Число является отрицательным
  • 1 – Число является положительным.

Sql(num) – Квадратный корень из переданного числового параметра num.

Следующие математические функции vba являются тригонометрическими. В качестве параметра для большинства указывается значение угла в радианах. Для перевода градусов в радианы используется формула:

Угол (в радианах) = угол (в градусах) * pi / 180, где pi = 3.14159265358979

Atn(par) – Арктангенс переданного числа (угол в радианах), функция вернет значение в диапазоне от -pi/2 до pi/2 радиан

Cos(par)  — Косинус переданного числа (угол в радианах), функция вернет значение в диапазоне от -1 до 1.

Sin(par)  — Синус переданного числа (угол в радианах), функция вернет значение в диапазоне от -1 до 1.

Tan(par)  — Тангенс переданного числа (угол в радианах).

Log(par)  – Натуральный логарифм переданного числа.

Я не буду приводить примеры для всех приведенных выше математических функций VBA, а приведу только один пример кода для функций sin и cos. Откройте редактор VBA (комбинация клавиш Alt + F11), добавьте в проект новый модуль (меню Insert/Module). В моем случае имя модуля – module3, в редакторе кода для заданного модуля пропишите следующие строки:

Sub Module3()
 
Dim oWord As Object, oDoc As Object, oSel As Object, oFont As Object
Dim i As Integer, j As Integer
i = 0: j = 0
Set oWord = CreateObject("Word.Application")
Set oDoc = oWord.Documents
oDoc.Add
Set oSel = oWord.Selection
oWord.Visible = True
Set oFont = oSel.Font
With oFont
    .Size = 15
    .Name = "Times New Roman"
    .Bold = True
    .ColorIndex = 2
End With
 
oSel.TypeText "Синус угла: от 0 до 360 с шагом 10"                                                                                                                          ' математические функции vba
With oFont
    .Size = 12
    .Bold = False
    .Bold = True
    .ColorIndex = 0
End With
 
oSel.TypeParagraph
oSel.TypeParagraph
 
Do While i <= 360
Dim my_var As String
my_var = Radianus(i)
    oSel.TypeText Sin(my_var) & vbTab & vbTab & "(" & i & ")"
    oSel.TypeParagraph
    i = i + 10
Loop
With oFont
    .Size = 15
    .Name = "Times New Roman"
    .Bold = True
    .ColorIndex = 2
End With
oSel.TypeParagraph
oSel.TypeParagraph
 
oSel.TypeText "Косинус угла: от 0 до 360 с шагом 10"                                                                                                                ' математические функции vba
With oFont
    .Size = 12
    .Bold = False
    .Bold = True
    .ColorIndex = 0
End With
 
oSel.TypeParagraph
oSel.TypeParagraph
 
Do While j <= 360
my_var = Radianus(j)
    oSel.TypeText Cos(my_var) & vbTab & vbTab & "(" & j & ")"
    oSel.TypeParagraph
    j = j + 10
Loop
 
End Sub
Function Radianus(c)
    Dim m_rad, m_pi
    m_pi = 3.14159265358979
    Radianus = c * m_pi / 180
End Function

В данном случае мы создаем новый документ Word, добавляем в него форматированный (объект Font) текст, содержащий параметры значений для синуса и косинуса. Я выбрал диапазон значений от 0 до 360 градусов, используя цикл vba do…loop.

Понравилась статья? Поделить с друзьями:
  • Функциональные ячейки в excel
  • Функция concatenate в excel по русски
  • Функциональные символы в excel
  • Функция concat в excel на русском
  • Функциональные клавиши для excel