2019-01-14

VBA - Function and Sub Procedure

VBA - User Defined Functions


1. Function 정의
Function getArea(Length As Double, Optional Width As Variant)
    Dim findArea As Double

    If IsMissing(Width) Then
       findArea = Length * Length    ''Square
    Else
       findArea = Length * Width     ''Area
    End If
    ''return: VBA has no return statement, instead using Function Name to return
    getArea = findArea
End Function

2. Function 호출

  • Sub procedure에서 호출
  • Excel 시트의 셀에서 직접 호출



VBA에서 함수(Function)는 Return문이 없다.
함수이름(getArea = '값')에 결과값을 대입하여 리턴하는 것에 주의해야 한다.


3. Sub Procedures
Sub Procedures 도 함수와 유사하지만, 몇 가지 다른 점이 있다.
  • Sub procedures는 Return값이 없다.
  • Sub procedures는 Sub 와 End Sub 문으로 구성된다.
Sub show_myArea()
    Dim 길이 As Double
    Dim  As Double
    Dim 면적 As Double
    길이 = 4
    폭 = 5
    ''Call function in sub procedure
    면적 = getArea(길이, 폭)
    
    Debug.Print 면적
    '' f(4,5) = 길이 * 폭 = 4 * 5 = 20
End Sub











No comments:

Post a Comment