사용 하면는 Const 문을 상수를 선언 하 고 해당 값을 설정 합니다.상수를 선언 하 여 값으로 의미 있는 이름을 할당 합니다.상수 선언 되 면 수정 또는 새 값을 지정할 수 없습니다.
프로시저 내에서 또는 모듈, 클래스 또는 구조체의 선언 섹션에는 상수를 선언합니다.클래스 또는 구조 수준 상수는 Private 기본적으로도로 선언할 수 있지만 Public, Friend, Protected, 또는 Protected Friend 적절 한 수준의 코드 액세스에 대 한 합니다.
올바른 심볼 이름을 (규칙은 변수 이름 만들기와 동일)와 숫자 또는 문자열 상수 및 연산자 (함수 호출 없음)의 구성 된 식의 상수 있어야 합니다.
참고
일부 Visual Studio 사용자 인터페이스 요소의 경우 다음 지침에 설명된 것과 다른 이름 또는 위치가 시스템에 표시될 수 있습니다.이러한 요소는 사용하는 Visual Studio 버전 및 설정에 따라 결정됩니다.자세한 내용은 IDE 개인 설정을 참조하세요.
때Option Infer은Off및Option Strict은On, 데이터 형식을 지정 하 여 명시적으로 상수를 선언 해야 합니다 (Boolean,Byte,Char,DateTime,Decimal,Double,Integer,Long,Short,Single, 또는String).
때Option Infer은On또는Option Strict은Off, 데이터 형식으로 지정 하지 않고 상수를 선언할 수 있습니다는As절.컴파일러에는 상수 식의 형식에서의 유형을 결정합니다.자세한 내용은 참조상수 및 리터럴 데이터 형식합니다.
코드 줄에 하나씩 단일 상수만 선언 하는 경우 더 쉽게 읽을 수는 있지만 한 줄에 여러 개의 상수를 선언할 수 있습니다.한 줄에 여러 개의 상수를 선언 하는 경우 이들은 모두 가져야 동일한 액세스 레벨 (Public,Private,Friend,Protected, 또는Protected Friend).
한 줄에 여러 개의 상수를 선언 하려면
다음 예제와 같이 공백, 쉼표와 선언을 구분 합니다.
Public Const Four As Integer = 4, Five As Integer = 5, Six As Integer = 44
삭제 선택된 항목에 대한 비주얼 베이직 도움말 보기 개체 찾아보기 다음 찾기 속성 창 시작 코드창으로 이동하기 중단점 설정/해제 전체선택 복사 파일 추가 메뉴 편집기 찾기 바꾸기 맨앞으로 가져오기 맨뒤로 호출 스택 새 프로젝트 프로젝트 열기 인쇄 프로젝트 탐색기 구성 요소 붙여넣기 조사식 편집 잘라내기 현재줄 잘라내기
전체 컴파일후 시작 커서까지 실행 다음 문 설정 한 단어만 지우기 해당 모듈의 끝으로 이동 해당 모듈의 처음으로 이동 이전 프로시저 선언으로 가기 다음 프로시저 선언으로 가기 한 단어만큼 오른쪽으로 이동 한 단어만큼 왼쪽으로 이동 이전 찾기 속성 페이지 다시 시작 개체 프로시저 단위 실행 간략한 조사식 오른쪽 마우스 버튼 클릭한것과 동일한 효과 오른쪽으로 한 단어 더 선택하기 왼쪽으로 선택된 한 단어 해제하기 위로 한 줄 더 선택하기/지우기 종료 매개 변수 정보 상수 목록 이전 위치 프로시저 나가기 모든 중단점 지우기
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
Part
Description
counter
Required in theForstatement. Numeric variable. The control variable for the loop. For more information, seeCounter Argumentlater in this topic.
datatype
Optional. Data type ofcounter. For more information, seeCounter Argumentlater in this topic.
start
Required. Numeric expression. The initial value ofcounter.
end
Required. Numeric expression. The final value ofcounter.
step
Optional. Numeric expression. The amount by whichcounteris incremented each time through the loop.
statements
Optional. One or more statements betweenForandNextthat run the specified number of times.
Continue For
Optional. Transfers control to the next loop iteration.
Exit For
Optional. Transfers control out of theForloop.
Next
Required. Terminates the definition of theForloop.
Note
TheTokeyword is used in this statement to specify the range for the counter. You can also use this keyword in theSelect...Case Statementand in array declarations. For more information about array declarations, seeDim Statement.
Simple Examples
You use aFor...Nextstructure when you want to repeat a set of statements a set number of times.
In the following example, theindexvariable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value ofindexreaches 5.
VB
For index AsInteger = 1To5
Debug.Write(index.ToString & " ")
Next
Debug.WriteLine("")
' Output: 1 2 3 4 5
In the following example, thenumbervariable starts at 2 and is reduced by 0.25 on each iteration of the loop, ending after the value ofnumberreaches 0. TheStepargument of-.25reduces the value by 0.25 on each iteration of the loop.
VB
For number AsDouble = 2To0Step-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
AWhile...End While StatementorDo...Loop Statementworks 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, aFor...Nextloop is a better choice. You determine the number of iterations when you first enter the loop.
Nesting Loops
You can nestForloops by putting one loop within another. The following example demonstrates nestedFor...Nextstructures 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 = 1To3' Create a new StringBuilder, which is used' to efficiently build strings.Dim sb AsNew System.Text.StringBuilder()
' Append to the StringBuilder every third number' from 20 to 1 descending.For indexB = 20To1Step-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 uniquecountervariable.
You can also nest different kinds control structures within each other. For more information, seeNested Control Structures.
Exit For and Continue For
TheExit Forstatement immediately exits theFor…Nextloop and transfers control to the statement that follows theNextstatement.
TheContinue Forstatement transfers control immediately to the next iteration of the loop. For more information, seeContinue Statement.
The following example illustrates the use of theContinue ForandExit Forstatements.
VB
For index AsInteger = 1To100000' If index is between 5 and 7, continue' with the next iteration.If index >= 5And index <= 8ThenContinueForEndIf' Display the index.
Debug.Write(index.ToString & " ")
' If index is 10, exit the loop.If index = 10ThenExitForEndIfNext
Debug.WriteLine("")
' Output: 1 2 3 4 9 10
You can put any number ofExit Forstatements in aFor…Nextloop. When used within nestedFor…Nextloops,Exit Forexits the innermost loop and transfers control to the next higher level of nesting.
Exit Foris often used after you evaluate some condition (for example, in anIf...Then...Elsestructure). You might want to useExit Forfor the following conditions:
Continuing to iterate is unnecessary or impossible. An erroneous value or a termination request might create this condition.
ATry...Catch...Finallystatement catches an exception. You might useExit Forat the end of theFinallyblock.
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 useExit Forto escape the loop. For more information, seeDo...Loop Statement.
Technical Implementation
When aFor...Nextloop starts, Visual Basic evaluatesstart,end, andstep. Visual Basic evaluates these values only at this time and then assignsstarttocounter. Before the statement block runs, Visual Basic comparescountertoend. Ifcounteris already larger than theendvalue (or smaller ifstepis negative), theForloop ends and control passes to the statement that follows theNextstatement. Otherwise, the statement block runs.
Each time Visual Basic encounters theNextstatement, it incrementscounterbystepand returns to theForstatement. Again it comparescountertoend, and again it either runs the block or exits the loop, depending on the result. This process continues untilcounterpassesendor anExit Forstatement is encountered.
The loop doesn't stop untilcounterhas passedend. Ifcounteris equal toend, the loop continues. The comparison that determines whether to run the block iscounter<=endifstepis positive andcounter>=endifstepis negative.
If you change the value ofcounterwhile inside a loop, your code might be more difficult to read and debug. Changing the value ofstart,end, orstepdoesn'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 theNextstatement of an outer nesting level before theNextstatement of an inner level. However, the compiler can detect this overlapping error only if you specifycounterin everyNextstatement.
Step Argument
The value ofstepcan be either positive or negative. This parameter determines loop processing according to the following table:
Step value
Loop executes if
Positive or zero
counter<=end
Negative
counter>=end
The default value ofstepis 1.
Counter Argument
The following table indicates whethercounterdefines a new local variable that’s scoped to the entireFor…Nextloop. This determination depends on whetherdatatypeis present and whethercounteris already defined.
Isdatatypepresent?
Iscounteralready defined?
Result (whethercounterdefines a new local variable that’s scoped to the entireFor...Nextloop)
No
Yes
No, becausecounteris already defined. If the scope ofcounterisn't local to the procedure, a compile-time warning occurs.
Yes, but only if the existingcountervariable is defined outside the procedure. That variable remains separate. If the scope of the existingcountervariable is local to the procedure, a compile-time error occurs.
Yes
No
Yes.
The data type ofcounterdetermines the type of the iteration, which must be one of the following types:
An enumeration that you declare by using anEnum Statement.
AnObject.
A typeTthat has the following operators, whereBis a type that can be used in aBooleanexpression.
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 thecountervariable in theNextstatement. This syntax improves the readability of your program, especially if you have nestedForloops. You must specify the variable that appears in the correspondingForstatement.
Thestart,end, andstepexpressions can evaluate to any data type that widens to the type ofcounter. If you use a user-defined type forcounter, you might have to define theCTypeconversion operator to convert the types ofstart,end, orstepto the type ofcounter.
우리가 VB Editor에서 작성하는 VBA 코드는 보통 '프로시저'라고 부르며, 가장 일반적인 프로시저는 Sub 프로시저와 Function 프로시저 입니다. 이 두 가지 프로시저의 가장 큰 차이점은,
Sub 프로시저 : 특정한 동작을 실행한다.
Function 프로시저 : 특정한 계산을 수행하고 그 결과값을 돌려준다.
김 판서가 두 명의 하인에게 똑같은 일거리를 주었습니다. 페인트를 한통씩 주고, "이제 봄이 되었으니 집 앞 담벼락에 페인트 칠을 해라!"하고... 한 나절이 지났습니다. 김 판서가 점검을 하러 나가 보았습니다. 갑돌이에게 맡긴 담벼락은 색칠을 되어 있는데 갑돌이는 어디론가 사라져 버리고 보이지 않는데, 삼돌이는 색칠을 마치고 주인에게 달려와서 결과를 보고합니다.
"저에게 주신 페인트 량은 100리터였는데, 담벼락의 넓이는 가로 10미터, 세로 2미터로 20 평방미터였습니다. 1 평방미터당 소요된 페인트 량이 0.3리터였으므로 60리터를 사용하여, 현재 40 리터의 페인트 재고가 남아 있습니다."
짐작하시겠지만, 여기서 갑돌이는 Sub 프로시저, 삼돌이는 Function 프로시저에 해당됩니다. 어떻습니까? Function 프로시저가 Sub 프로시저보다 더 똑똑해 보이지요? 앞으로는 똘똘한 Function 프로시저만 사용해야 되겠다는 생각이 드시나요?
하지만 세상은 공평한 것... 머리가 똑똑하면 얼굴이 받쳐주지 않고, 외모가 되면 머리가 따라주지 않는 것이 보통이지요. 머리도 똑똑하고 외모도 예술이면... 하다 못해 성격이 괴팍하다거나 팔자가 드세다거나 하는 등, 이 세상에 모든 것을 다 갖춘 사람은 없는 법이지요. Function 프로시저가 Sub 프로시저에 비해 지능은 뛰어난 반면 제약이 있습니다.
Function 프로시저는 다른 말로 사용자 정의 함수라고도 부릅니다. 모든 Function 프로시저는 Function 이라는 키워드로 시작해서 End Function 이라는 statement로 끝을 맺습니다. 사용자 정의 함수의 기본적인 작성 형식은 이러합니다.
Function 함수명(인수1, 인수2,...)
... 어쩌고 ...
... 저쩌고 ...
함수명 = 결과값
End Function
제곱근을 구해주는 사용자 정의 함수를 만들어 보면,
Function 제곱근(number, n)
제곱근 = 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) '도구-매크로-매크로' 메뉴를 선택하니다. (2) '매크로 이름' 항목에 해당 함수의 이름을 입력합니다. ('매크로' 대화상자에는 사용자 정의 함수의 이름이 표시되지 않습니다) (3) '옵션' 버튼을 클릭합니다. (4) '설명' 항목에 함수에 대한 자세한 설명을 기입합니다. (5) '확인' 버튼을 클릭합니다. (6) '취소' 버튼을 클릭합니다.
새로운 함수 범주를 만들 수 있을까?
함수 범주를 새로이 추가할 수는 없습니다. 또한 사용자 정의 함수의 인수argument에 세부적인 설명을 추가할 수도 없습니다. 대신 사용자 정의 함수의 인수 이름을 의미있는 것으로 지정해 주면 어느 정도는 직관적으로 이해할 수 있게 되므로 편리합니다.
원래 이번 강좌는 계획에 없던 것입니다만, 오피스 튜터에서 가졌던 [Excel VBA 활용 과정]을 수강하신 분들에게 설명드린 내용을 정리하면서 포함하는 것이 좋을 것 같아 작성하였습니다.
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 한 단계씩 코드 실행