사용 하면는 Const 문을 상수를 선언 하 고 해당 값을 설정 합니다. 상수를 선언 하 여 값으로 의미 있는 이름을 할당 합니다. 상수 선언 되 면 수정 또는 새 값을 지정할 수 없습니다.

프로시저 내에서 또는 모듈, 클래스 또는 구조체의 선언 섹션에는 상수를 선언합니다. 클래스 또는 구조 수준 상수는 Private 기본적으로도로 선언할 수 있지만 PublicFriendProtected, 또는 Protected Friend 적절 한 수준의 코드 액세스에 대 한 합니다.

올바른 심볼 이름을 (규칙은 변수 이름 만들기와 동일)와 숫자 또는 문자열 상수 및 연산자 (함수 호출 없음)의 구성 된 식의 상수 있어야 합니다.

참고

일부 Visual Studio 사용자 인터페이스 요소의 경우 다음 지침에 설명된 것과 다른 이름 또는 위치가 시스템에 표시될 수 있습니다. 이러한 요소는 사용하는 Visual Studio 버전 및 설정에 따라 결정됩니다. 자세한 내용은 IDE 개인 설정을 참조하세요.

상수 선언 하려면

  • 액세스 지정자를 포함 하는 선언을 작성 된 Const 키워드 및 다음 예와 같이 식:

    VB
    Public Const DaysInYear = 365
    Private Const WorkDays = 250
    

     Option Infer  Off  Option Strict  On, 데이터 형식을 지정 하 여 명시적으로 상수를 선언 해야 합니다 (Boolean, Byte, Char, DateTime, Decimal, Double, Integer, Long, Short, Single, 또는 String).

     Option Infer  On 또는 Option Strict  Off, 데이터 형식으로 지정 하지 않고 상수를 선언할 수 있습니다는 As 절. 컴파일러에는 상수 식의 형식에서의 유형을 결정합니다. 자세한 내용은 참조 상수 및 리터럴 데이터 형식합니다.

으로 명시적으로 지정된 하는 데이터 형식이 지정 된 상수를 선언 하려면

  • 포함 하는 선언을 작성는 As 키워드 및 명시적 데이터 형식, 다음 예제와 같이:

    VB
    Public Const MyInteger As Integer = 42
    Private Const DaysInWeek As Short = 7
    Protected Friend Const Funday As String = "Sunday"
    

    코드 줄에 하나씩 단일 상수만 선언 하는 경우 더 쉽게 읽을 수는 있지만 한 줄에 여러 개의 상수를 선언할 수 있습니다. 한 줄에 여러 개의 상수를 선언 하는 경우 이들은 모두 가져야 동일한 액세스 레벨 (Public, Private, Friend, Protected, 또는 Protected Friend).

한 줄에 여러 개의 상수를 선언 하려면

  • 다음 예제와 같이 공백, 쉼표와 선언을 구분 합니다.

    Public Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44  


'Knowledge > Visual Basic 6+' 카테고리의 다른 글

VB6 단축키  (0) 2018.04.19
[VB6] 전역변수 선언 (Not Global keyword)  (0) 2018.04.02
[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26
VB 단축키 모음

 단축키

실행 내용 

단축키 

실행 내용 

Tab
Shift+Tab
Shift+F2
F8
Ctrl+I
Ctrl+J
Crtl+아래쪽 화살표

들여쓰기
내어쓰기
정의(루틴검색)
한 단계씩 코드 실행
요약 정보
속성/메서드 목록
다음 프로시저의 첫번째 줄로 이동

Crtl+위쪽 화살표
Ctrl+SpaceBar
Ctrl+S
Ctrl+Z
Ctrl+G
Ctrl+Break

 

이전 프로시저의 첫번째 줄로 이동
단어 채우기
저장
실행취소
직접 실행 창
중단

Del
F1
F2
F3
F4
F5
F7
F9
Ctrl+A
Ctrl+C
Ctrl+D
Ctrl+E
Ctrl+F
Ctrl+H
Ctrl+J
Ctrl+K
Ctrl+L
Ctrl+N
Ctrl+O
Ctrl+P
Ctrl+R
Ctrl+T
Ctrl+V
Ctrl+W
Ctrl+X
Ctrl+Y

삭제
선택된 항목에 대한 비주얼 베이직 도움말 보기
개체 찾아보기
다음 찾기
속성 창
시작
코드창으로 이동하기
중단점 설정/해제
전체선택
복사
파일 추가
메뉴 편집기
찾기
바꾸기
맨앞으로 가져오기
맨뒤로
호출 스택
새 프로젝트
프로젝트 열기
인쇄
프로젝트 탐색기
구성 요소
붙여넣기
조사식 편집
잘라내기
현재줄 잘라내기

Ctrl+F5
Ctrl+F8
Ctrl+F9
Crtl+DEL
Crtl+End
Crtl+Home
Crtl+Page Up
Crtl+Page down
Crtl+오른쪽 화살표
Crtl+왼쪽 화살표
Shift+F3
Shift+F4
Shift+F5
Shift+F7
Shift+F8
Shift+F9
Shift+F10
Shift+오른쪽 화살표
Shift+왼쪽 화살표
Shift+아래쪽 화살표
Alt+Q
Ctrl+Shift+I
Ctrl+Shift+J
Ctrl+Shift+F2
Ctrl+Shift+F8
Ctrl+Shift+F9

전체 컴파일후 시작
커서까지 실행
다음 문 설정
한 단어만 지우기
해당 모듈의 끝으로 이동
해당 모듈의 처음으로 이동
이전 프로시저 선언으로 가기
다음 프로시저 선언으로 가기 
한 단어만큼 오른쪽으로 이동
한 단어만큼 왼쪽으로 이동
이전 찾기
속성 페이지
다시 시작
개체
프로시저 단위 실행
간략한 조사식
오른쪽 마우스 버튼 클릭한것과 동일한 효과
오른쪽으로 한 단어 더 선택하기
왼쪽으로 선택된 한 단어 해제하기
위로 한 줄 더 선택하기/지우기
종료
매개 변수 정보
상수 목록
이전 위치
프로시저 나가기
모든 중단점 지우기

 

키보드로 컨트롤 다루기

 SHIFT + RIGHT ARROW

 컨트롤의 폭(width)을 증가시킵니다.

 CONTROL + RIGHT ARROW

 컨트롤을 오른쪽으로 움직입니다.

 SHIFT + LEFT ARROW

 컨트롤의 폭(width)을 감소시킵니다.

 CONTROL + LEFT ARROW

 컨트롤을 왼쪽으로 움직입니다.

 SHIFT + DOWN ARROW

 컨트롤의 높이(height)을 증가시킵니다.

 CONTROL + DOWN ARROW

 컨트롤을 아래로 움직입니다.

 SHIFT + UP ARROW

 컨트롤의 높이(height)을 감소시킵니다.

 CONTROL + UP ARROW

 컨트롤을 위로 움직입니다.


'Knowledge > Visual Basic 6+' 카테고리의 다른 글

[VB6] 상수 선언  (0) 2018.05.09
[VB6] 전역변수 선언 (Not Global keyword)  (0) 2018.04.02
[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26

' 전역변수 선언은 이렇게 밖에다 할 수 있다.

' Global keyword는 vb6에서는 사용되지 않는다.


Public LogName As String


Private Sub AddItem_Init(key As String, value As String)

    

    Dim category As String

    Dim message As String

    

    LogName = "practice.ini"

    category = "General"

    message = "[key]:{key}   [value]:{value}"

    

    message = Replace(message, "{key}", key)

    message = Replace(message, "{value}", value)

    

    

    Call fn_WritePrivateProfileString(LogName, category, key, value)

    Call sb_SaveLog(App.EXEName, message)

    

End Sub

'Knowledge > Visual Basic 6+' 카테고리의 다른 글

[VB6] 상수 선언  (0) 2018.05.09
VB6 단축키  (0) 2018.04.19
[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26

Replace Function - Visual Basic 6.0 (VB 6.0)

Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Syntax:
Replace(expression, find, replace[, start[, count[, compare]]])
ParameterDescription
expressionRequired. String expression containing substring to replace.
findRequired. Substring being searched for.
replaceRequired. Replacement substring.
startOptional. Default 1. Position within expression where substring search is to begin.
countOptional. Default -1 (All). Number of substring substitutions to perform.
compareOptional. Default vbBinaryCompare (0). Numeric value indicating the kind of comparison to use when evaluating substrings.

Return Data type:
String
Example:

Dim St as String
St = "Chennaiiq"


StatementResultRemark
Replace(St, "n", "m")Chemmaiiq 
Replace(St, "N", "m")Chennaiiq 
Replace(St, "n", "M")CheMMaiiq 
Replace(St, "n", "m", 5)maiiq 
Replace(St, "n", "m", 4, 1)mnaiiq 
Replace("", "n", "m") Empty String
Replace(null, "n", "m")ErrorInvalid use of null
Replace(St, "", "m")Chennaiiq(Copy of Expression)
Replace(St, "n", "")Cheaiiq 
Replace(St, "n", "m", 20) Empty String
Replace(St, "n", "m", 1, 0)Chennaiiq 


'Knowledge > Visual Basic 6+' 카테고리의 다른 글

VB6 단축키  (0) 2018.04.19
[VB6] 전역변수 선언 (Not Global keyword)  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26
For...Next Statement (Visual Basic)  (0) 2018.03.13

VB6 문법 모음 페이지


# Call Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/call-statement


# Error Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/error-statement


# DO...Loop Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/do-loop-statement


# Exit Statement

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/exit-statement

vb6 What is Me.Caption


Hi, starting out in vb and working through some exercises and am confronted with a line of code

OldCaption = Me.Caption

The question is what is Me."xxxxxxxxx" and what applications can it be used for.


Many thanks in advance...Andy


--------------------------------------------------------------------------------------------------------------------------------


What is Me?

Me is the form itself. It is just a shorthand of using the form name. So Me.Caption and Formname.Caption is the same.



  OldCaption = Me.Caption

Above code simply saves the caption of the form to a variable named OldCaption.


hongjun


For...Next Statement (Visual Basic)

Repeats a group of statements a specified number of times.

Syntax

For counter [ As datatype ] = start To end [ Step step ]  
    [ statements ]  
    [ Continue For ]  
    [ statements ]  
    [ Exit For ]  
    [ statements ]  
Next [ counter ]  

Parts

PartDescription
counterRequired in the For statement. Numeric variable. The control variable for the loop. For more information, see Counter Argument later in this topic.
datatypeOptional. Data type of counter. For more information, see Counter Argument later in this topic.
startRequired. Numeric expression. The initial value of counter.
endRequired. Numeric expression. The final value of counter.
stepOptional. Numeric expression. The amount by which counter is incremented each time through the loop.
statementsOptional. One or more statements between For and Next that run the specified number of times.
Continue ForOptional. Transfers control to the next loop iteration.
Exit ForOptional. Transfers control out of the For loop.
NextRequired. Terminates the definition of the For loop.

Note

The To keyword is used in this statement to specify the range for the counter. You can also use this keyword in the Select...Case Statement and in array declarations. For more information about array declarations, see Dim Statement.

Simple Examples

You use a For...Next structure when you want to repeat a set of statements a set number of times.

In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.

VB
For index As Integer = 1 To 5
    Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5

In the following example, the number variable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value of number reaches 0. The Step argument of -.25 reduces the value by 0.25 on each iteration of the loop.

VB
For number As Double = 2 To 0 Step -0.25
    Debug.Write(number.ToString & " ")
Next
Debug.WriteLine("")
' Output: 2 1.75 1.5 1.25 1 0.75 0.5 0.25 0 

Tip

A While...End While Statement or Do...Loop Statement works well when you don't know in advance how many times to run the statements in the loop. However, when you expect to run the loop a specific number of times, a For...Next loop is a better choice. You determine the number of iterations when you first enter the loop.

Nesting Loops

You can nest For loops by putting one loop within another. The following example demonstrates nested For...Next structures that have different step values. The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter variable for every iteration of the loop.

VB
For indexA = 1 To 3
    ' Create a new StringBuilder, which is used
    ' to efficiently build strings.
    Dim sb As New System.Text.StringBuilder()

    ' Append to the StringBuilder every third number
    ' from 20 to 1 descending.
    For indexB = 20 To 1 Step -3
        sb.Append(indexB.ToString)
        sb.Append(" ")
    Next indexB

    ' Display the line.
    Debug.WriteLine(sb.ToString)
Next indexA
' Output:
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2
'  20 17 14 11 8 5 2

When nesting loops, each loop must have a unique counter variable.

You can also nest different kinds control structures within each other. For more information, see Nested Control Structures.

Exit For and Continue For

The Exit For statement immediately exits the ForNext loop and transfers control to the statement that follows the Next statement.

The Continue For statement transfers control immediately to the next iteration of the loop. For more information, see Continue Statement.

The following example illustrates the use of the Continue For and Exit For statements.

VB
For index As Integer = 1 To 100000
    ' If index is between 5 and 7, continue
    ' with the next iteration.
    If index >= 5 And index <= 8 Then
        Continue For
    End If

    ' Display the index.
    Debug.Write(index.ToString & " ")

    ' If index is 10, exit the loop.
    If index = 10 Then
        Exit For
    End If
Next
Debug.WriteLine("")
' Output: 1 2 3 4 9 10

You can put any number of Exit For statements in a ForNext loop. When used within nested ForNextloops, Exit For exits the innermost loop and transfers control to the next higher level of nesting.

Exit For is often used after you evaluate some condition (for example, in an If...Then...Else structure). You might want to use Exit For for the following conditions:

  • Continuing to iterate is unnecessary or impossible. An erroneous value or a termination request might create this condition.

  • A Try...Catch...Finally statement catches an exception. You might use Exit For at the end of the Finally block.

  • You have an endless loop, which is a loop that could run a large or even infinite number of times. If you detect such a condition, you can use Exit For to escape the loop. For more information, see Do...Loop Statement.

Technical Implementation

When a For...Next loop starts, Visual Basic evaluates start, end, and step. Visual Basic evaluates these values only at this time and then assigns start to counter. Before the statement block runs, Visual Basic compares counter to end. If counter is already larger than the end value (or smaller if step is negative), the For loop ends and control passes to the statement that follows the Next statement. Otherwise, the statement block runs.

Each time Visual Basic encounters the Next statement, it increments counter by step and returns to the Forstatement. Again it compares counter to end, and again it either runs the block or exits the loop, depending on the result. This process continues until counter passes end or an Exit For statement is encountered.

The loop doesn't stop until counter has passed end. If counter is equal to end, the loop continues. The comparison that determines whether to run the block is counter <= end if step is positive and counter >= end if step is negative.

If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.

If you nest loops, the compiler signals an error if it encounters the Next statement of an outer nesting level before the Next statement of an inner level. However, the compiler can detect this overlapping error only if you specify counter in every Next statement.

Step Argument

The value of step can be either positive or negative. This parameter determines loop processing according to the following table:

Step valueLoop executes if
Positive or zerocounter <= end
Negativecounter >= end

The default value of step is 1.

Counter Argument

The following table indicates whether counter defines a new local variable that’s scoped to the entire For…Nextloop. This determination depends on whether datatype is present and whether counter is already defined.

Is datatypepresent?Is counteralready defined?Result (whether counter defines a new local variable that’s scoped to the entire For...Next loop)
NoYesNo, because counter is already defined. If the scope of counter isn't local to the procedure, a compile-time warning occurs.
NoNoYes. The data type is inferred from the start, end, and step expressions. For information about type inference, see Option Infer Statement and Local Type Inference.
YesYesYes, but only if the existing counter variable is defined outside the procedure. That variable remains separate. If the scope of the existing counter variable is local to the procedure, a compile-time error occurs.
YesNoYes.

The data type of counter determines the type of the iteration, which must be one of the following types:

  • A Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double.

  • An enumeration that you declare by using an Enum Statement.

  • An Object.

  • A type T that has the following operators, where B is a type that can be used in a Booleanexpression.

    Public Shared Operator >= (op1 As T, op2 As T) As B

    Public Shared Operator <= (op1 As T, op2 As T) As B

    Public Shared Operator - (op1 As T, op2 As T) As T

    Public Shared Operator + (op1 As T, op2 As T) As T

You can optionally specify the counter variable in the Next statement. This syntax improves the readability of your program, especially if you have nested For loops. You must specify the variable that appears in the corresponding For statement.

The start, end, and step expressions can evaluate to any data type that widens to the type of counter. If you use a user-defined type for counter, you might have to define the CType conversion operator to convert the types of start, end, or step to the type of counter.

Exceller's VBA 입문강좌

최초 작성일 : 2005-03-21
최종 수정일 : 2005-03-21

강좌 읽음수 : 106,935회
자료 작성자 : Exceller (권현욱, exceller@amorepacific.com)

강좌 제목 : Sub 프로시저와 Function 프로시저

그리스의 철학자 에픽테투스는 이런 말을 했습니다.

"인간은 일어난 사건에 의해서가 아니라 그 사건에 대한 자신의 의견 때문에 고통을 느끼게 되는 것이다."

불가능이란 "사실"이 아니라 자신의 약한 의지와 다른 사람들의 잘못된 "의견"이 덧붙여진 것일 따름입니다.

무엇을 해도 좋은 계절, 봄이 오고 있습니다. 이번 봄에 꼭 이루고 싶은 것이 하나 있습니다. 그것이 무엇이냐 하면... 비밀이랍니다. ^^* 여러분은 이 봄에 이루고 싶은 어떤 꿈을 가지고 계신가요?


VBA 입문강좌 : Sub 프로시저와 Function 프로시저


 이번 시간에는 Sub 프로시저와 Function 프로시저의 차이점, 그리고 Function 프로시저, 즉 사용자 정의 함수의 기본 개념과 응용 예제들에 대해 살펴봅니다.
 

Sub 프로시저와 Function 프로시저의 차이

우리가 VB Editor에서 작성하는 VBA 코드는 보통 '프로시저'라고 부르며, 가장 일반적인 프로시저는 Sub 프로시저와 Function 프로시저 입니다. 이 두 가지 프로시저의 가장 큰 차이점은,

  • Sub 프로시저 : 특정한 동작을 실행한다.

  • Function 프로시저 : 특정한 계산을 수행하고 그 결과값을 돌려준다.

김 판서가 두 명의 하인에게 똑같은 일거리를 주었습니다. 페인트를 한통씩 주고, "이제 봄이 되었으니 집 앞 담벼락에 페인트 칠을 해라!"하고... 한 나절이 지났습니다. 김 판서가 점검을 하러 나가 보았습니다. 갑돌이에게 맡긴 담벼락은 색칠을 되어 있는데 갑돌이는 어디론가 사라져 버리고 보이지 않는데, 삼돌이는 색칠을 마치고 주인에게 달려와서 결과를 보고합니다.

"저에게 주신 페인트 량은 100리터였는데, 담벼락의 넓이는 가로 10미터, 세로 2미터로 20 평방미터였습니다. 1 평방미터당 소요된 페인트 량이 0.3리터였으므로 60리터를 사용하여, 현재 40 리터의 페인트 재고가 남아 있습니다."

짐작하시겠지만, 여기서 갑돌이는 Sub 프로시저, 삼돌이는 Function 프로시저에 해당됩니다. 어떻습니까? Function 프로시저가 Sub 프로시저보다 더 똑똑해 보이지요? 앞으로는 똘똘한 Function 프로시저만 사용해야 되겠다는 생각이 드시나요?

하지만 세상은 공평한 것... 머리가 똑똑하면 얼굴이 받쳐주지 않고, 외모가 되면 머리가 따라주지 않는 것이 보통이지요. 머리도 똑똑하고 외모도 예술이면... 하다 못해 성격이 괴팍하다거나 팔자가 드세다거나 하는 등, 이 세상에 모든 것을 다 갖춘 사람은 없는 법이지요. Function 프로시저가 Sub 프로시저에 비해 지능은 뛰어난 반면 제약이 있습니다.

Sub 프로시저

보통 여러분이 VBA에서 작성하는 코드는 Sub 프로시저입니다. 매크로 기록기를 이용해서 작성한 코드 역시 Sub 프로시저입니다. 모든 Sub  프로시저는 Sub 라는 키워드로 시작해서 End Sub라는 statement로 끝을 맺습니다.

Sub 안녕하세요()

    MsgBox "안녕하세요 " & Application.UserName & "님!"

End Sub

프로시저명 뒤에는 항상 한 쌍의 괄호가 붙습니다. 보통의 경우, 이 괄호 안에는 아무 것도 들어있지 않지만, 필요한 경우 argument, 즉 인수를 전달하여 실행을 할 수도 있습니다.

Function 프로시저

Function 프로시저는 다른 말로 사용자 정의 함수라고도 부릅니다. 모든 Function  프로시저는 Function 이라는 키워드로 시작해서 End Function 이라는 statement로 끝을 맺습니다. 사용자 정의 함수의 기본적인 작성 형식은 이러합니다.

Function 함수명(인수1, 인수2,...)

    ... 어쩌고 ...

    ... 저쩌고 ...

    함수명 = 결과값

End Function

제곱근을 구해주는 사용자 정의 함수를 만들어 보면,

Function 제곱근(numbern)

    제곱근 = number ^ (1/n)

End Function

여기서 number는 제곱근을 구하고자 하는 값(숫자), n은 몇 제곱근을 구할 것인지를 지정하는 인수입니다. 예를 들어, 위의 코드를 모듈시트에 작성한 다음, 워크시트 내 임의의 셀에 "=제곱근(2,2)" 라고 입력하면 2의 2제곱근 값인 "1.414213..." 라는 결과값이 구해집니다.

Function, 즉 함수는 몇 개의 인수를 가질 수도 있고 전혀 가지지 않을 수도 있습니다(Today, Now, Rand 등과 같이...).

Function 프로시저는 딱 두 가지 방법에 의해서만 실행할 수 있습니다.

  (1) 다른 프로시저(Sub 혹은 Function 프로시저)에서 호출하는 방법
  (2) 워크시트 내에서 수식의 형태로 사용하는 방법

반면, Sub 프로시저는 아주 다양한 방법으로 실행할 수 있는데, 이것이 사람들로 하여금 Sub 프로시저를 더 많이 사용하게 하는 한 가지 이유가 되기도 합니다.

  (1) VBE에서 '표준' 도구모음에 있는 'Sub/사용자 정의 폼 실행' 아이콘 이용
  (2) VBE에서 '실행-Sub/사용자 정의 폼 실행' 메뉴 이용
  (3) VBE에서 '직접 실행 창'에서 바로 실행 ← Sub 프로시저명 입력/엔터
  (4) 단축 키를 통해 실행(Ctrl + 단축 키) ← 단축 키가 미리 지정되어 있을 경우
  (5) 다른 Sub 프로시저에서 호출하여 실행
  (6) 워크시트에서 버튼이나 도형 등의 개체에 연결하여 실행
  (7) '도구-매크로-매크로' 메뉴를 통해 실행
  (8) 도구 모음의 사용자 지정 단추에 연결하여 실행
  (9) 사용자 지정 메뉴에 연결하여 실행
  (10) 특정한 이벤트가 발생하였을 때 실행 ← 이벤트 프로시저에 연결하여

참으로 많은 방법이 있기도 하지요? 이것 말고도 더 있을 지도 모릅니다. 그리고 Function 프로시저는 Sub 프로시저에서 쉽게 할 수 있는 글꼴을 변경한다거나 셀의 색상을 변경한다거나 하는 작업은 할 수 없습니다. 
 

사용자 정의 함수 예제

(1) 인수를 하나도 가지지 않는 사용자 정의 함수

Function UserName()

    UserName = Application.UserName

End Function

'=UserName()' 이라고 입력하면 현재 사용자의 이름이 표시됩니다.

 

(2) 상여금 계산 사용자 정의 함수

아래과 같은 사원 기본정보가 있다고 할 때, 직종에 따라 성과급을 차등 지급하는 사용자 정의 함수를 작성해 보겠습니다.

Function 성과급(직종코드, 연봉)

    Select Case 직종코드
        Case 1
            성과급 = 연봉 * 0.1
        Case 2, 3
            성과급 = 연봉 * 0.08
        Case 4 To 7
            성과급 = 1000000
        Case Is > 7
            성과급 = 500000
        End Select

End Function

이 함수를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

 

(3) 선택적 인수Optional argument를 가지는 사용자 정의 함수

특정한 범위 내에서 상위 5개 값의 평균을 구해야 한다면 어떻게 해야 할까요? 엑셀에는 그런 기능을 수행하는 함수가 따로 없기 때문에 다음과 같은 형태의 수식을 사용해야 할 것입니다.

= (Large(영역, 1) + Large(영역, 2) + ... + Large(영역, 5)) / 5

물론 이 수식은 오류없이 제대로 작동합니다. 하지만 그다지 좋은 해결 방법이라고 하기는 어렵습니다. 왜냐고요? 모로가도 어디로만 가면 되지 않느냐구요?? 그렇다면... 만약 상위 10개 값의 평균을 구해야 한다면 수식을,

= (Large(영역, 1) + Large(영역, 2) + ... + Large(영역, 10)) / 10

이런 식으로 바꾸어 주실 것입니까? 그러면 100개 값의 평균은 어떻습니까? 곤란하겠지요? 이런 경우 사용자 정의 함수를 만들면 간단히 해결할 수 있습니다.

Function 상위평균(rngX, Optional n = 5)

    Dim dblSum As Double
    Dim i As Integer

    For i = 1 To n
        dblSum = dblSum + Application.WorksheetFunction.Large(rngX, i)
    Next i

    상위평균 = dblSum / n

End Function

여기서... Optional 이라는 새로운 단어가 하나 나왔군요. 우리가 잘 아는 Left 함수를 생각해 보면,

Left(텍스트, 추출할 문자 수)

이런 형식으로 사용됩니다. 만약 '추출할 문자 수' 인수를 생략하면 엑셀이 알아서 1로 간주합니다. 즉 다음 두 수식은 같은 결과값을 돌려줍니다.

= Left(A1, 1)
= Left(A1)

이처럼, 사용자 정의 함수에서 특정한 인수를 생략하면 기본적으로 어떤 값을 갖도록 설정할 때 사용하는 것이 Optional 키워드입니다.

(4) 인수의 개수가 정해져 있지 않은 사용자 정의 함수

어떤 워크시트 함수는 인수의 개수가 미리 정해져 있지 않은 것이 있습니다. 어떤 것이 있을까요? 대표적인 것으로 Sum 함수가 있습니다.

= Sum(number1, number2,...)

이런 식으로 30개 까지의 인수를 가질 수 있습니다. 여기서 첫번째 인수는 반드시 있어야 하지만 나머지 인수는 상황에 따라 변합니다. 이런 함수는 어떻게 하면 만들 수 있을까요? ParamArray 키워드를 사용하면 가능합니다.

Function MySum(ParamArray XXX() As Variant) As Double
    Dim varX As Variant

    For Each varX In XXX
        MySum = MySum + varX
    Next varX
End Function
 

ParamArray 키워드는 항상 Variant 데이터 타입이며, 항상 선택적 인수Optional argument입니다. 설령 Optonal 키워드를 사용하지 않았더라도 말입니다.

사용자 정의 함수 범주 변경하기

기본적으로 사용자 정의 함수는 '사용자 정의' 범주에 포함되어 있습니다. VBA를 이용하면 이 범주를 변경할 수 있습니다(왜 그렇게 만들었는지 이유를 알 수는 없지만, 워크시트 상태에서 수작업으로는 바꾸어 줄 방법이 없습니다).

 

MacroOptions 메서드를 사용하여 다음과 같이 해 주면 '상위평균'이라는 사용자 정의 함수의 범주가 수학/삼각함수 범주로 변경됩니다.

Sub ChangeCategory()
    Application.MacroOptions macro:="상위평균", Category:=3
End Sub

<MacroOption 메서드의 기본 제공 범주>

함수 범주

0

모두

1

재무

2

날짜/시간

3

수학/삼각

4

통계

5

찾기/참조 영역

6

데이터베이스

7

텍스트

8

논리

9

정보

10

Commands(이 범주는 화면상에 표시되지 않습니다)

11

Customizing(이 범주도 숨겨져 있습니다)

12

Macro Control(이 범주도 숨겨져 있습니다)

13

DDE/External(이 범주도 숨겨져 있습니다)

14

사용자 정의(Default)

15

공학(분석 도구를 추가 설치한 경우 나타납니다)

사용자 정의 함수 설명 추가하기

'함수 마법사' 대화상자에서 엑셀의 워크시트 함수를 선택해 보면 해당 함수에 대한 간단한 설명이 나타나는 것을 볼 수 있습니다. 하지만 사용자 정의 함수에 대해서도 마찬가지로 이러한 설명이 나타나도록 할 수 있습니다.

 

  (1) '도구-매크로-매크로' 메뉴를 선택하니다.
  (2) '매크로 이름' 항목에 해당 함수의 이름을 입력합니다.
       ('매크로' 대화상자에는 사용자 정의 함수의 이름이 표시되지 않습니다)
  (3) '옵션' 버튼을 클릭합니다.
  (4) '설명' 항목에 함수에 대한 자세한 설명을 기입합니다.
  (5) '확인' 버튼을 클릭합니다.
  (6) '취소' 버튼을 클릭합니다.

   새로운 함수 범주를 만들 수 있을까?

함수 범주를 새로이 추가할 수는 없습니다. 또한 사용자 정의 함수의 인수argument에 세부적인 설명을 추가할 수도 없습니다. 대신 사용자 정의 함수의 인수 이름을 의미있는 것으로 지정해 주면 어느 정도는 직관적으로 이해할 수 있게 되므로 편리합니다.

원래 이번 강좌는 계획에 없던 것입니다만, 오피스 튜터에서 가졌던 [Excel VBA 활용 과정]을 수강하신 분들에게 설명드린 내용을 정리하면서 포함하는 것이 좋을 것 같아 작성하였습니다.

이번 강좌는 여기까지...
 


 Previous

Next 

 

ⓒ 2005 Exceller Corporation. All rights reserved.


1.    F1 : 선택된 항목에 대한 비주얼 베이직 도움말 보기
2.    F2 : 개체 찾아보기
3.    F3 : 다음 찾기
4.    F5 : 컴파일하기
5.    Crtl+F5 : 전체 컴파일한 후 다시 시작하기
6.    Crtl+F : 찾아보기 (Find)
7.    Crtl+H : 바꾸기
8.    Crtl+I : 변수등의 요약 정보
9.    Crtl+J : 속성과 메소드 목록보기
10.    Crtl+Z : 실행 취소
11.    Crtl+DEL : 한 단어만 지우기
12.    Crtl+오른쪽 화살표 : 한 단어만큼 오른쪽으로 이동
13.    Crtl+왼쪽 화살표 : 한 단어만큼 왼쪽으로 이동
14.    Crtl+Home : 해당 모듈의 처음으로 이동
15.    Crtl+End : 해당 모듈의 끝으로 이동
16.    Crtl+아래쪽 화살표 : 다음 프로시저의 첫번째 줄로 이동
17.    Crtl+위쪽 화살표 : 이전 프로시저의 첫번째 줄로 이동
18.    Crtl+Page Up : 이전 프로시저 선언으로 가기
19.    Crtl+Page down : 다음 프로시저 선언으로 가기
20.    Crtl+스페이스바 : 나머지 단어 채우기
21.    Shift+F2 : 프로시저 정의 보기
22.    Shift+F3 : 이전 찾기
23.    Shift+F10 : 오른쪽 마우스 버튼 클릭한것과 동일한 효과
24.    Shift+Tab : 선택된 부분의 들여쓰기 해제
25.    Shift+오른쪽 화살표 : 오른쪽으로 한 단어 더 선택하기
26.    Shift+왼쪽 화살표 : 왼쪽으로 선택된 한 단어 해제하기
27.    Shift+아래쪽 화살표 : 위로 한 줄 더 선택하기/지우기
28.    Ctrl+Shift+F2 : 가장 마지막으로 가기
29.    Ctrl+Shift+J : 상수 열거
30.    Ctrl+Shift+I : 인수 정보 보기


  1. Shift + F2        : 선언된 함수, 변수로 이동하기
  2. Shift + Ctrl + F2 : Shift + F2 로 가서 되돌아오기
  3. F8                : 한문장씩 실행하기(중지모드에서 사용)
  4. Shift + F8        : 어떤 문장이 사용자 정의 함수를 호출할시
                         F8키는 함수안으로 들어가지만, Shift + F8 키는
                         함수를 모두 실행하고 다음 문장으로 이동합니다.
                         (중지모드에서 사용)
  5. Ctrl + F9         : 노란색선을 원하는 위치로 이동하기
                         중지모드에서 현재 실행중인 코드가 노란색으로
                         나타납니다. 마우스나 키보드로 특정문장으로
                         커서를 이동 시킨뒤 Ctrl + F9키를 누르면 
                         여기부터 다시 실행할 수 있습니다.
  6. Ctrl + SpaceBar   : 단어채우기
                         코딩중 긴함수나 긴변수를 일일히 쓰는건 아주
                         짜증나는 일입니다. 만약 변수명이 mintRecordCount
                         일 경우 mintR 한다음에 Ctrl + SpaceBar를
                         누르면 단어가 자동으로 채워 집니다. 
                         (중복 단어가 있으면 골라서 사용할 수 있습니다.)
  7. 꽁수(....^^)
     만약 어떤 이벤트를 테스트할 목적으로 디버깅 하려면 여러분들은
     보통 어떤식으로 하십니까?... 아마 그 이벤트에 F9키를 눌러서
     중단점을 잡아 놓고서 F5키를 눌러서 실행 할 것입니다.
     그런데 중단점을 잡아 놓지 않고, 할수 있는 방법이 있는데 그 방법을
     설명해 드리겠습니다...

     먼저 실행도중에 Ctrl + Break키를 눌러서 중지모드 상태로 들어갑니다.
     다음에 F8키를 누르고, 어떤 이벤트(버튼클릭 또는 키보드 입력 ....)를 
     발생시키면 디버깅 상태로 들어갈 것입니다.(전재조건 : 발생시킨 이벤트 
     안에는 반드시 코드가 있어야겠죠...)



단축키(ShortCut Key) 설명 
   CTRL+C              선택영역 복사하기  
   CTRL+X              선택영역 잘라내기 
   CTRL+Y              현재줄 잘라내기  
   CTRL+V              붙여넣기  
   CTRL+DELETE         문장단위로 지우기 
   TAB                 선택영역 한번에 내여쓰기  
   SHIFT+TAB           선택영역 한번에 들여쓰기  
   CTRL+Z              되돌리기(실행취소)  
   CTRL+RIGHT ARROW    다음 단어로 이동  
   CTRL+LEFT ARROW     이전 단어로 이동  
   CTRL+DOWN ARROW     다음 프로시져로 이동  
   CTRL+UP ARROW       이전 프로시져로 이동 
   SHIFT+F2            정의 보기  
   CTRL+F              찾기  
   CTRL+H              바꾸기  
   CTRL+S              저장하기  
   F7                  코드창으로 이동하기 
   F4                  속성창으로 이동하기  
   CTRL+R              프로젝트 탐색기로 이동하기  
   F5                  실행  
   F8                  한 단계씩 코드 실행

'Knowledge > Visual Basic 6+' 카테고리의 다른 글

[VB6] Replace Function - Visual Basic 6.0  (0) 2018.04.02
Visual Basic 문법  (0) 2018.03.27
[VB6] What is Me.Caption  (0) 2018.03.26
For...Next Statement (Visual Basic)  (0) 2018.03.13
Sub 프로시저와 Function 프로시저  (0) 2018.03.13

+ Recent posts