본문 바로가기
언어 참조

상수 선언 및 사용

2023. 7. 28.

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

상수 선언

상수를 선언하면 값에 의미 있는 이름을 지정할 수 있습니다. Const 문을 사용하여 상수를 선언하고 값을 설정합니다. 상수를 선언한 후에는 수정하거나 새 값을 할당할 수 없습니다.

Sub Example_ConstantDeclaration()
    ' 상수 선언
    Const PI As Double = 3.14159
    Const TaxRate As Double = 0.1
    Const MaxAttempts As Integer = 3
    
    ' 변수 선언
    Dim radius As Double
    Dim area As Double
    Dim price As Double
    Dim numberOfAttempts As Integer
    
    ' 원의 넓이 계산
    radius = 5
    area = PI * radius * radius
    Debug.Print "원의 넓이: " & area
    
    ' 제품 가격 계산
    price = 100
    price = price + (price * TaxRate)
    Debug.Print "세금 포함 가격: " & price
    
    ' 로그인 시도 횟수 확인
    numberOfAttempts = 0
    Do While numberOfAttempts < MaxAttempts
        numberOfAttempts = numberOfAttempts + 1
        Debug.Print "로그인 시도 #" & numberOfAttempts
    Loop
End Sub

프로시저 내에서 또는 모듈 상단의 선언 섹션에서 상수를 선언할 수 있습니다. 모듈 수준 상수는 기본적으로 비공개입니다. 공개 모듈 수준 상수를 선언하려면 Const 문 앞에 Public 키워드를 추가합니다. 코드를 더 쉽게 읽고 해석할 수 있도록 Const 문 앞에 Private 키워드를 사용하여 비공개 상수를 명시적으로 선언할 수 있습니다.

Private Const MaxValue As Integer = 100
Private Const MinValue As Integer = 1

Sub Example_Constants()
    
    Const PI As Double = 3.14159
    
    Dim radius As Double
    Dim area As Double
    Dim value As Integer
    
    radius = 5
    area = PI * radius * radius
    Debug.Print "원의 넓이: " & area

  
    value = MaxValue
    If value > MinValue Then
        Debug.Print "Value is within the valid range."
    End If
    
    Debug.Print "MaxValue: " & MaxValue
    Debug.Print "MinValue: " & MinValue
    
End Sub

Private Const PI_PRIVATE As Double = 3.14159
Public Const PI_PUBLIC As Double = 3.14159

Sub ExampleFunction()
   
    Const LOCAL_CONSTANT As Integer = 10

       Dim result1 As Double
    result1 = PI_PRIVATE * 2

       Dim result2 As Double
    result2 = PI_PUBLIC * 2
    
       Dim result3 As Integer
    result3 = LOCAL_CONSTANT * 2
    
     Debug.Print "Private constant (PI_PRIVATE) result: " & result1 & vbCrLf _
    & "Public constant (PI_PUBLIC) result: " & result2 & vbCrLf _
    & "Local constant (LOCAL_CONSTANT) result: " & result3
End Sub

Public Const PI As Double = 3.14159
Public Const MaxValue As Integer = 100
Public Const CurrencyRate As Currency = 1.23456
Public Const IsDebugMode As Boolean = True
Public Const TodayDate As Date = #7/28/2023#
Public Const GreetingMessage As String = "Hello, world!"

Sub Example_Constants()
    
    Dim radius As Double
    Dim area As Double
    Dim value As Integer
    Dim totalAmount As Currency
    Dim isDebug As Boolean
    Dim currentDate As Date
    Dim message As String

    radius = 5
    area = PI * radius * radius
    Debug.Print "Circle's area: " & area

    value = 75
    If value <= MaxValue Then
        Debug.Print "Value is within the valid range."
    End If

    totalAmount = 500 * CurrencyRate
    Debug.Print "Total amount in local currency: " & totalAmount

    isDebug = IsDebugMode
    If isDebug Then
        Debug.Print "Debug mode is enabled."
    End If

    currentDate = TodayDate
    Debug.Print "Today's date: " & currentDate

    message = GreetingMessage
    Debug.Print message
End Sub

다음 예제에서는 공용 상수 conAge를 정수로 선언하고 34라는 값을 할당합니다.

Public Const conAge As Integer = 34

상수는 다음 데이터 유형 중 하나로 선언할 수 있습니다: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String, or Variant

Sub Example_Constants()
    ' Boolean
    Const IsEnabled As Boolean = True
    
    ' Numeric data types
    Const ByteValue As Byte = 100
    Const IntegerValue As Integer = 1000
    Const LongValue As Long = 1000000
    Const CurrencyValue As Currency = 1234.56
    Const SingleValue As Single = 3.14
    Const DoubleValue As Double = 3.1415926535
    
    ' Date
    Const TodayDate As Date = #7/28/2023#
    
    ' String
    Const GreetingMessage As String = "Hello, world!"
    
    ' Variant
    Const AnyValue As Variant = "This is a variant constant."
    
    ' Output the constant values
    Debug.Print "Boolean constant (IsEnabled): " & IsEnabled
    Debug.Print "Byte constant (ByteValue): " & ByteValue
    Debug.Print "Integer constant (IntegerValue): " & IntegerValue
    Debug.Print "Long constant (LongValue): " & LongValue
    Debug.Print "Currency constant (CurrencyValue): " & CurrencyValue
    Debug.Print "Single constant (SingleValue): " & SingleValue
    Debug.Print "Double constant (DoubleValue): " & DoubleValue
    Debug.Print "Date constant (TodayDate): " & TodayDate
    Debug.Print "String constant (GreetingMessage): " & GreetingMessage
    Debug.Print "Variant constant (AnyValue): " & AnyValue
End Sub

하나의 문에 여러 상수를 선언할 수 있습니다. 데이터 유형을 지정하려면 각 상수에 대한 데이터 유형을 포함해야 합니다.

Sub Example_MultipleConstants()
    ' 여러 상수를 하나의 문에 선언하고 데이터 유형 지정
    Const PI As Double = 3.14159, TaxRate As Double = 0.1
    Const MaxValue As Integer = 100, MinValue As Integer = 0
    Const GreetingMessage As String = "Hello, world!", ErrorMessage As String = "An error occurred!"
    
    ' 상수 사용
    Dim radius As Double
    Dim area As Double
    Dim price As Double
    Dim value As Integer
    Dim message As String

    ' 원의 넓이 계산
    radius = 5
    area = PI * radius * radius
    Debug.Print "원의 넓이: " & area

    ' 제품 가격 계산
    price = 100
    price = price + (price * TaxRate)
    Debug.Print "세금 포함 가격: " & price

    ' 값이 유효한지 확인
    value = 75
    If value >= MinValue And value <= MaxValue Then
        Debug.Print "값이 유효합니다."
    End If

    ' 메시지 출력
    message = GreetingMessage
    Debug.Print message

    ' 에러 메시지 출력
    message = ErrorMessage
    Debug.Print message
End Sub

도움말 출처

 

 

Declaring constants (VBA)

Office VBA reference topic

learn.microsoft.com

상수 사용

코드에 자주 발생하는 상수 값이 포함되어 있거나 기억하기 어렵고 의미가 분명하지 않은 특정 숫자에 의존할 수 있습니다. 상수를 사용하면 코드를 더 쉽게 읽고 유지 관리할 수 있습니다. 상수는 변하지 않는 숫자나 문자열을 대신하는 의미 있는 이름입니다. 상수는 변수처럼 수정하거나 새 값을 할당할 수 없습니다.

상수의 종류

상수에는 세 가지 유형이 있습니다.

내장 상수 또는 시스템 정의 상수는 응용 프로그램 및 컨트롤에서 제공됩니다. Microsoft Access, Excel, Project 및 Word와 같이 개체 라이브러리를 제공하는 다른 응용 프로그램에서도 해당 개체, 메서드 및 속성과 함께 사용할 수 있는 상수 목록을 제공합니다. 개체 브라우저에서 개별 개체 라이브러리에 대해 제공되는 상수 목록을 가져올 수 있습니다.

Visual Basic 상수는 Visual Basic for Applications 형식 라이브러리 및 DAO(Data Access Object) 라이브러리에 나열됩니다.

 메모

Visual Basic에서는 이전 버전의 Visual Basic 또는 Visual Basic for Applications에서 만든 응용 프로그램의 상수를 계속 인식합니다. 상수를 개체 브라우저에 나열된 상수로 업그레이드할 수 있습니다. 개체 브라우저에 나열된 상수는 응용 프로그램에서 선언할 필요가 없습니다.

기호 상수 또는 사용자 정의 상수는 Const 문을 사용하여 선언됩니다.

조건부 컴파일러 상수는 #Const 문(지시문)을 사용하여 선언됩니다.

접두사로 상수 한정하기

모든 객체에서 제공하는 내재 상수는 대/소문자 혼용 형식으로 표시되며, 상수를 정의하는 객체 라이브러리를 나타내는 두 글자 접두사가 붙습니다. Visual Basic for Applications 객체 라이브러리의 상수는 접두사 앞에 "vb"가 붙고, Microsoft Excel 객체 라이브러리의 상수는 접두사 앞에 "xl"이 붙습니다. 다음 예는 유형 라이브러리에 따라 사용자 지정 컨트롤의 접두사가 어떻게 달라지는지 보여줍니다.

라이브러리 참조로 상수 한정하기

다음 구문을 사용하여 상수에 대한 참조를 한정할 수도 있습니다.

[ libname.] [ modulename.] constname

libname : 선택 사항입니다. 상수를 정의하는 유형 라이브러리의 이름입니다. 대부분의 사용자 지정 컨트롤(매킨토시에서는 사용할 수 없음)의 경우 컨트롤의 클래스 이름이기도 합니다. 컨트롤의 클래스 이름이 기억나지 않는 경우 도구 상자에서 마우스 포인터를 컨트롤 위에 놓습니다. 클래스 이름이 도구 설명에 표시됩니다.

modulename : 선택 사항입니다. 상수를 정의하는 유형 라이브러리 내 모듈의 이름입니다. 객체 브라우저를 사용하여 모듈의 이름을 찾을 수 있습니다.

constname : 유형 라이브러리에서 상수에 대해 정의된 이름입니다.

 

예시입니다.

VBA.VbMsgBoxResult
Word.WdAlignmentTabAlignment

 

도움말 출처

 

Using constants (VBA)

Office VBA reference topic

learn.microsoft.com

 

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

범위와 가시성 이해하기  (0) 2023.07.28
Variant 이해하기  (0) 2023.07.28
데이터 타입을 효율적으로 사용하기  (0) 2023.07.28
변수 선언  (0) 2023.07.28
Visual Basic 명명 규칙  (0) 2023.07.28