본문 바로가기
언어 참조

변수의 수명 이해

2023. 7. 29.

이 글은 도움말을 번역한 내용입니다.

변수가 값을 유지하는 시간을 수명이라고 합니다. 변수의 값은 수명 동안 변경될 수 있지만 어느 정도의 값은 유지됩니다. 변수가 범위를 잃으면 더 이상 값을 갖지 않습니다.

프로시저 실행이 시작되면 모든 변수가 초기화됩니다. 숫자 변수는 0으로 초기화되고, 가변 길이 문자열은 길이가 0인 문자열("")로 초기화되며, 고정 길이 문자열은 ASCII 문자 코드 0 또는 Chr( 0 )으로 표시되는 문자로 채워집니다. 변형 변수는 비워짐으로 초기화됩니다. 사용자 정의 유형 변수의 각 요소는 마치 별도의 변수인 것처럼 초기화됩니다.

' User-defined type variable (사용자 정의형 변수) - 각 요소별로 초기화됨
    Type MyType ' 사용자 정의형 선언
        name As String
        age As Integer
        isStudent As Boolean
    End Type

Sub ExampleVariableInitialization()
    ' 변수 초기화와 관련된 예제

    ' Numeric variable (숫자 변수) - 초기값: 0
    Dim numVar As Integer ' Integer 변수는 0으로 초기화됨
    Debug.Print "numVar: " & numVar ' 결과: 0

    ' Variable-length string (가변 길이 문자열) - 초기값: ""
    Dim strVar As String ' 문자열 변수는 빈 문자열("")로 초기화됨
    Debug.Print "strVar: " & strVar ' 결과: ""

    ' Fixed-length string (고정 길이 문자열) - 초기값: Chr(0) 또는 바이트 0
    Dim fixedStrVar As String * 5 ' 길이가 5인 문자열 변수는 Chr(0)으로 초기화됨
    Debug.Print "fixedStrVar: " & fixedStrVar ' 결과: "    " (5개의 NULL 문자)

    ' Variant variable (Variant 변수) - 초기값: Empty
    Dim variantVar As Variant ' Variant 변수는 Empty로 초기화됨
    Debug.Print "variantVar: " & variantVar ' 결과: Empty

    
    Dim userVar As MyType ' 사용자 정의형 변수 선언
    Debug.Print "userVar.name: " & userVar.name ' 결과: "" (빈 문자열)
    Debug.Print "userVar.age: " & userVar.age ' 결과: 0 (정수 변수는 0으로 초기화)
    Debug.Print "userVar.isStudent: " & userVar.isStudent ' 결과: False (Boolean 변수는 False로 초기화)
End Sub

개체 변수를 선언하면 메모리에 공간이 예약되지만 Set 문을 사용하여 객체 참조를 할당할 때까지 해당 값은 Nothing으로 설정됩니다.

코드를 실행하는 동안 변수 값이 변경되지 않으면 범위가 사라질 때까지 초기화된 값을 유지합니다.

(예제에서는 initialNum)

Dim 문으로 선언된 프로시저 수준 변수는 프로시저 실행이 완료될 때까지 값을 유지합니다. 프로시저가 다른 프로시저를 호출하는 경우 해당 프로시저가 실행되는 동안에도 변수는 해당 값을 유지합니다.

Sub MainProcedure()
    Dim procedureLevelVar As Integer ' 절차 수준 변수 선언
    procedureLevelVar = 10 ' 변수 초기화
    ' MainProcedure 내에서 값을 변경하지 않으므로 초기 설정된 값 10을 유지
    Call SecondProcedure(procedureLevelVar)

    ' 호출된 다른 프로시저(SecondProcedure)가 실행되는 동안 값이 유지됩니다.
    Debug.Print "MainProcedure의 procedureLevelVar 값: " & procedureLevelVar
End Sub
Sub SecondProcedure(procedureLevelVar As Integer)
    Dim result As Integer
    result = procedureLevelVar * 2
    Debug.Print "SecondProcedure의 procedureLevelVar 값: " & procedureLevelVar
    Debug.Print "결과 값: " & result ' 결과 값 출력
End Sub

Sub MainProcedure()
    Dim procedureVariable As Integer
    procedureVariable = 10
    Debug.Print "MainProcedure - Before calling SubProcedure1: " & procedureVariable
    SubProcedure1
    Debug.Print "MainProcedure - After calling SubProcedure1: " & procedureVariable
End Sub

Sub SubProcedure1()
    Dim subProcedureVariable As Integer
    subProcedureVariable = 5
    Debug.Print "SubProcedure1 - subProcedureVariable: " & subProcedureVariable
    subProcedureVariable = subProcedureVariable + 2
    Debug.Print "SubProcedure1 - subProcedureVariable after addition: " & subProcedureVariable
End Sub

프로시저 수준 변수를 Static 키워드로 선언하면 모듈에서 코드가 실행되는 한 변수는 해당 값을 유지합니다. 모든 코드의 실행이 완료되면 변수는 범위와 값을 잃게 됩니다. 변수의 수명은 모듈 수준 변수와 동일합니다.

Sub ExampleProcedure()
    Static counter As Integer
    counter = counter + 1
    
    ' 변수 counter의 값을 출력합니다.
    Debug.Print "프로시저가 실행된 횟수: " & counter
End Sub

Sub TestExampleProcedure()
    ' ExampleProcedure을 세 번 실행하여 Static 변수 counter의 값을 확인합니다.
    ExampleProcedure
    ExampleProcedure
    ExampleProcedure
End Sub

Sub MainProcedure()
    Dim normalVariable As Integer
    Static staticVariable As Integer

    normalVariable = normalVariable + 1
    staticVariable = staticVariable + 1

    Debug.Print "Normal Variable: " & normalVariable
    Debug.Print "Static Variable: " & staticVariable

    SubProcedure1
    SubProcedure2

    Debug.Print "Normal Variable after SubProcedures: " & normalVariable
    Debug.Print "Static Variable after SubProcedures: " & staticVariable
End Sub

Sub SubProcedure1()
    Dim localVar As Integer
    localVar = 5
    Debug.Print "SubProcedure1 - Local Variable: " & localVar
End Sub

Sub SubProcedure2()
    Static staticVar As Integer
    staticVar = staticVar + 10
    Debug.Print "SubProcedure2 - Static Variable: " & staticVar
End Sub

모듈 수준 변수는 정적 변수와 다릅니다. 표준 모듈이나 클래스 모듈에서는 코드 실행을 중단할 때까지 해당 값을 유지합니다. 클래스 모듈에서는 클래스의 인스턴스가 존재하는 한 해당 값을 유지합니다. 모듈 수준 변수는 값을 재설정할 때까지 메모리 리소스를 소모하므로 필요한 경우에만 사용하세요.

' 모듈 수준 변수 선언
Dim moduleCounter As Integer

Sub IncrementCounter()
    moduleCounter = moduleCounter + 1
    Debug.Print "모듈 수준 변수에 대한 카운터 값: " & moduleCounter
End Sub

Sub TestModuleLevelVariable()
    IncrementCounter
    IncrementCounter
    IncrementCounter
End Sub

' 클래스 모듈에서 모듈 수준 변수 선언
Dim classCounter As Integer

Public Sub IncrementCounter()
    classCounter = classCounter + 1
End Sub

Public Function GetCounter() As Integer
    GetCounter = classCounter
End Function
Sub TestClassLevelVariable()
    ' MyClass 인스턴스 생성
    Dim myInstance1 As MyClass
    Set myInstance1 = New MyClass
    
    myInstance1.IncrementCounter
    myInstance1.IncrementCounter
    
    ' 변수 값 출력
    Debug.Print "클래스 인스턴스1의 카운터 값: " & myInstance1.GetCounter

    ' 또 다른 인스턴스 생성
    Dim myInstance2 As MyClass
    Set myInstance2 = New MyClass
    
    myInstance2.IncrementCounter
    
    ' 변수 값 출력
    Debug.Print "클래스 인스턴스2의 카운터 값: " & myInstance2.GetCounter
End Sub

Sub 또는 Function 문 앞에 Static 키워드를 포함하면 프로시저의 모든 프로시저 수준 변수 값이 호출 간에 보존됩니다.

Static Function ExampleFunction() As Integer
    Dim counter As Integer
    counter = counter + 1
    
    ExampleFunction = counter
End Function

Sub TestStaticFunction()
    Dim result1 As Integer, result2 As Integer, result3 As Integer
    
    ' Static Function 호출
    result1 = ExampleFunction()
    result2 = ExampleFunction()
    result3 = ExampleFunction()
    
    ' 결과 출력
    Debug.Print "Function 호출 결과: " & result1 & ", " & result2 & ", " & result3
End Sub

도움말 출처

Understanding the lifetime of variables (VBA)

Office VBA reference topic

learn.microsoft.com

'언어 참조' 카테고리의 다른 글

Let 문  (0) 2023.07.29
대입문 작성  (0) 2023.07.29
범위와 가시성 이해하기  (0) 2023.07.28
Variant 이해하기  (0) 2023.07.28
상수 선언 및 사용  (0) 2023.07.28