2019-01-04

VBA - Basics

VBA - Basics
1. Module
모듈은 코드를 작성하는 영역으로 매크로 기록을 처음으로 작성하는 경우 Module이 만들어 진다. 워크북에서 VBA Editor창을 열고 삽입 메뉴에서 모듈을 선택하여 생성할 수 있다.


2. Procedure
프로시져는 한번에 실행될 명령의 모음이다. 엑셀에게 특정한 작업을 수행하도록 지시한다.
단순한 프로시져부터 복잡한 프로시져까지 만들 수 있지만, 복잡한 것은 작게 나누어 작성하여 유지보수를 쉽게 하는 것이 좋다.
함수의 코드는 Sub 과 End Sub 사이에 위치한다.
https://gist.github.com/SeongilRyu/6c541219ca325bef40cb9401c37b0edb
Public Sub prc_add()
''프로시져 예제
Dim 가로 As Integer
Dim 세로 As Integer
Dim 면적 As Integer
가로 = 3
세로 = 4
면적 = 가로 * 세로
MsgBox 면적
''
'' 결과: 12
End Sub



3. Function
펑션, 함수는 재사용 가능한 코드의 모음이다., 프로그램의 어디에서든지 호출 가능하며 리턴되는 값이 있다. 
기본으로 엑셀에 포함된 함수외에, VBA로 사용자 정의 함수를 만들 수 있다.
함수의 코드는 Function 과 End Function 사이에 위치한다.
https://gist.github.com/SeongilRyu/ec60bd70f8e9b3dc0aa3d106b5c070d4
Function fnc_add(width As Integer, height As Integer)
''함수 예제
Dim 가로 As Integer
Dim 세로 As Integer
Dim 면적 As Integer
가로 = width
세로 = height
면적 = 가로 * 세로
MsgBox 면적
fnc_add 면적 ''return value
''
'' 결과: 입력 변수에 따른 결과
End Function


4. Comments
Single Quote(') 또는 'Rem' 시작하는 문장은 Comments이다. 명령로직의 설명 문서와 프로그램 작성자의 의도를 알 수 있게 한다.
' This line is comment.  
' Written by : Author VBA Tutorial 
REM 이 줄은 코멘트입니다.  
Rem 작성자 : VBA 강좌

5. MessageBox and InputBox
Message box는 메세지 창에 메세지를 표시한다.
Sub show_Message() 
   '메세지박스 표시 ("Hello VBA.!")     

   MsgBox "Hello VBA.!" 

End Sub
Input box는 사용자의 입력을 받을 수 있다.
두 개의 Inputbox가 있으며, Application.InputBox는 셀의 값을 참조로 받을 수 있다.
Sub show_Inputbox() 
   '사용자 입력 박스로 입력을 받는다.
   Dim 가로 As Integer
   Dim 세로 As Integer
   Dim 면적 As Integer
   가로 = InputBox("가로 입력 ", "숫자를 입력하시오")
   세로 = Application.InputBox("세로 입력 ", "숫자를 입력/셀선택 하시오")
   면적 = 가로 * 세로
   MsgBox 면적

End Sub















6. 변수(Variables)
Variable 은 값을 담을 수 있는 메모리 이름이다. 스크립트가 실행되는 중에 값은 변경될 수 있다.
Sub show_variables()
''변수(Variable)
''Type별 변수 정의

    Dim var_bool As Boolean
    Dim var_byte As Byte
    Dim var_int As Integer
    Dim var_long As Long
    Dim var_single As Single
    Dim var_double As Double
    ''
    Dim var_string As String
    Dim var_date As Date
    Dim var_variant As Variant
    ''
    var_bool = False
    var_byte = 255
    var_int = 32767
    var_long = 2147483647#
    var_single = 3.402823E+38
    var_double = 1.79769313486232E+307
    
    var_string = "1 to 65,400 characters"
    var_date = DateValue("30 / 10 / 2020")
    var_object = "Some Object"
    var_variant = "Number or String"
    
    Debug.Print var_bool & vbCrLf & _
                var_byte & vbCrLf & _
                var_int & vbCrLf & _
                var_long & vbCrLf & _
                var_single & vbCrLf & _
                var_double & vbCrLf & _
                var_string & vbCrLf & _
                var_date & vbCrLf & _
                var_variant & vbCrLf

End Sub
Constants
값이 변할 수 있는 변수와는 다르게 항상 고정된 값을 가지는 상수이다.
Const MyInteger As Integer = 24 
Const 나의정수 As Integer = 24


7. 연산자(Operators)
VBA는 수치, 논리, 관계 연산자를 제공하고, 문자열을 연결하는 Concatenation 연산자가 있다.
Operator Description Example
+ Adds the two operands 10 + 5 will give 15
- Subtracts the second operand from the first 10 - 5 will give -5
* Multiplies both the operands 10 * 5 will give 50
/ Divides the numerator by the denominator 5 / 10 will give 2
% Modulus operator and the remainder after an integer division 5 % 10 will give 0
^ Exponentiation operator 5 ^ 10 will give 100000
= Checks if the value of the two operands are equal or not. If yes, then the condition is true. (10 = 20) is False.
<> Checks if the value of the two operands are equal or not. If the values are not equal, then the condition is true. (10 <> 20) is True.
> Checks if the value of the left operand is greater than the value of the right operand. If yes, then the condition is true. (10 > 20) is False.
< Checks if the value of the left operand is less than the value of the right operand. If yes, then the condition is true. (10 < 20) is True.
>= Checks if the value of the left operand is greater than or equal to the value of the right operand. If yes, then the condition is true. (10 >= 20) is False.
<= Checks if the value of the left operand is less than or equal to the value of the right operand. If yes, then the condition is true. (10 <= 20) is True.
AND Called Logical AND operator. If both the conditions are True, then the Expression is true. 10<>0 AND 0<>0 is False.
OR Called Logical OR Operator. If any of the two conditions are True, then the condition is true. 10<>0 OR 0<>0 is true.
NOT Called Logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make false. NOT(10<>0 OR 0<>0) is false.
XOR Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to be True, the result is True. (10<>0 XOR 0<>0) is true.
& Concatenates two Values "Microsoft" & "VBA" will give MicrosoftVBA


8. 조건(Decision)
조건문 if, if-else, if-elseif, nested if,  Switch문으로 프로그램의 흐름을 제어한다.
Sub show_conditions()
''1. if-statement
   If 234 > 34 Then
      MsgBox "234 is Greater than 34"
   End If
   
''2. if-else
    Dim X, Y As Integer
    X = 234
    Y = 432
   If X > Y Then
      MsgBox "X is Greater than Y"
   Else
      MsgBox "Y is Greater than X"
   End If

''3. if-elseif
   X = 234
   Y = 234
   If X > Y Then
      MsgBox "X is Greater than Y"
   ElseIf Y > X Then
      MsgBox "Y is Greater than X"
   Else
      MsgBox "X and Y are EQUAL"
   End If
   
''4. 중첩 if
   Dim a As Integer
   a = 23
   If a > 0 Then
      MsgBox "a가 양수인 경우"
      If a = 1 Then
         MsgBox "The Number is 1"
      Else
         MsgBox "The Number is NOT 1"
      End If
   End If

''5. switch
   Dim MyVar As Integer
   MyVar = 1
   Select Case MyVar
      Case 1
         MsgBox "첫번째 수"
      Case 2
         MsgBox "중간 수"
      Case 3
         MsgBox "마지막 수"
      Case Else
         MsgBox "Unknown Number"
   End Select
End Sub


8. 반복(Loop)
VBA 에서 for-loop, for-each-loop, do-while-loop등을 사용한다.
Sub show_loops()
'''1. for-loop
   Dim a As Integer
   a = 8
   
   For i = 0 To a Step 2
      MsgBox "The value is i is : " & i
   Next
   
'''2. for-each-loop
    Dim fruits As Variant
    ''fruits는 배열
    fruits = Array("apple", "orange", "cherries")
 
   'iterating using For each loop.
    For Each Item In fruits
       Debug.Print Item & Chr(10)
    Next
   
''3. do-while-loop
    Dim x As Integer
    x = 3
   Do While x < 5
      x = x + 1
      MsgBox "The value of x is : " & x
   Loop
End Sub

9. 문자열(String) 함수
Strings은 일련의 문자열이다. 알파벳, 숫자, 특수문자로 구성된다. 변수에 담기는 스트링은 겹따옴표( " ")로 표현한다.

Sub show_strings()
Dim str As String
str = "Microsoft VBA"
''1. InStr: 문자가 나타난 첫번째 위치
Debug.Print InStr(str, "VBA") ''Result= 11
''2. InStrRev: 역순으로 문자가 나타난 첫번째 위치
Debug.Print InStrRev(str, "VBA") ''Result= 11
''3. LCase: 소문자로 변경
Debug.Print LCase(str) ''Result= microsoft vba
''4. UCase: 대문자로 변경
Debug.Print UCase(str) ''Result= MICROSOFT VBA
''
''5. Left: 왼쪽부터 주어진 숫자만큰 문자를 자르기
Debug.Print Left(str, 5) ''Result= Micro
''6. Right: 오른쪽부터 주어진 숫자만큰 문자를 자르기
Debug.Print Right(str, 5) ''Result= t VBA
''7. Mid: 6자리부터 7문자 자르기
Debug.Print Mid(str, 6, 7) ''Result= soft VB
''
''8. LTrim: 왼쪽의 공백 제거
Debug.Print LTrim(str) ''Result= Microsoft VBA
''9. RTrim: 오른쪽의 공백 제거
Debug.Print RTrim(str) ''Result= Microsoft VBA
''10. Trim: 공백 제거
Debug.Print Trim(str) ''Result= Microsoft VBA
''
''11. Len: 문자열의 길이
Debug.Print Len(str) ''Result= 13
''12. Replace: 문자열의 치환
Debug.Print Replace(str, "Microsoft", "Google") ''Result= Google VBA
''13. Space: 공백 삽입
Debug.Print str & Space(10) & "Tutorial" ''Result= Microsoft VBA Tutorial
''
''14. StrComp: 문자열 비교
Debug.Print StrComp(str, "Google VBA") ''Result= 1
''15. String: 주어진 문자열 삽입
Debug.Print String(3, "$") ''Result= $$$
''16. StrReverse: 역순으로 문자열 표시
Debug.Print StrReverse(str) ''Result= ABV tfosorciM
End Sub
view raw VBA_strings.bas hosted with ❤ by GitHub

10. 날짜와 시간(Date and Time) 함수
VBA에서는 날짜와 시간 함수를 사용하여 시스템 날짜를 가져오거나 다른 포맷으로 표현할 수 있다.

11. 배열(Array)
변수는 하나의 값을 가진다. 때로는 여러개의 값을 가질 수 있는 하나의 변수가 필요하다.
일련의 값들을 저장하기 위해 Array변수를 사용한다.

Array변수를 선언하고 값을 지정한다.

Multi-dimensional array
다차원 배열도 선언할 수 있고 값을 지정할 수 있다.


ReDim

초기에는 배열의 크기를 지정하지 않고 나중에 사용될 때 크기를 지정할때 ReDim을 사용한다.
=gist=
Sub arrays_declare()
'방법 1 : Dim 사용
Dim arr1() 'Size 없이 선언
'방법 2 : Size를 지정하여 선언
Dim arr2(5) '사이트 5를 지정
'방법 3 : 'Array' 파라메터 사용
Dim arr3
arr3 = Array("사과","오렌지","포도")
End Sub
Sub array_assign()
''배열에 값 지정
Dim arr(5)
arr(0) = "1" '숫자 문자
arr(1) = "VBA" '문자
arr(2) = 100 '숫자
arr(3) = 3.14 '십진수
arr(4) = #2019-01-13# '날짜
arr(5) = #12.45 PM# '시간
msgbox("Array index 0의 값 : " & arr(0))
msgbox("Array index 1의 값 : " & arr(1))
msgbox("Array index 2의 값 : " & arr(2))
msgbox("Array index 3의 값 : " & arr(3))
msgbox("Array index 4의 값 : " & arr(4))
msgbox("Array index 5의 값 : " & arr(5))
End Sub
Sub array_multi_dimension()
''다차원 배열
Dim arr(2,3) as Variant ' (row 3, col 4)
arr(0,0) = "row 0, col 0"
arr(0,1) = "row 0, col 1"
arr(0,2) = "row 0, col 2"
arr(0,3) = "row 0, col 3"
arr(1,0) = "row 1, col 0"
arr(1,1) = "row 1, col 1"
arr(1,2) = "row 1, col 2"
arr(1,3) = "row 1, col 3"
arr(2,0) = "row 2, col 0"
arr(2,1) = "row 2, col 1"
arr(2,2) = "row 2, col 2"
arr(2,3) = "row 2, col 3"
msgbox("Array index 0,1의 값 : " & arr(0,1))
msgbox("Array index 2,2의 값 : " & arr(2,2))
End Sub
Sub arrays_redim()
''Size없이 배열 선언
Dim a() as variant
i = 0
''redim으로 크기 지정
redim a(3)
a(0) = "XYZ"
a(1) = 3.14
a(2) = 275
'배열값 확인
For i = 0 to UBound(a)
Msgbox a(i)
Next
End Sub
Sub array_split()
'Split function: 구분자로 분리될 수 있는 문자열을 분리하여 배열로 만든다.
' 구분자(delimiter) comma ','
Dim a as Variant
a = Split("Red,Blue,Yellow",",")
For i = 0 to UBound(a)
msgbox("Value" & i & " is :" & a(i))
Next
End Sub
Sub array_join()
'Join function: Split 함수의 반대 개념.
' 배열 항목들을 구분하여 문자열을 만든다.
a = array("Red","Blue","Yellow")
' Join using $
b = join(a,"$")
msgbox("The Join result after using delimiter is : " & b)
''Red$Blue$Yellow
End Sub
Sub array_filter()
'Filter function: 필터 조건에 맞는 항목만 선택된 배열을 만든다.
Dim a,b,c,d as Variant
a = array("Red","Blue","Yellow")
b = Filter(a,"B")
c = Filter(a,"e")
d = Filter(a,"Y")
For each x in b
msgbox("The Filter result 1: " & x)
Next
For each y in c
msgbox("The Filter result 2: " & y)
Next
For each z in d
msgbox("The Filter result 3: " & z)
Next
End Sub
Sub array_erase()
' IsArray function: 배열인지 아닌지 확인(True, False)
Dim a,b as Variant
a = array("Red","Blue","Yellow")
b = "12345"
If IsArray(a) = True then
Erase a ' 각 배열의 항목이 초기화 된다.
' Dynamic Array인 경우 사용된 메모리가 Free된다.
End If
End Sub
view raw VBA_arrays.bas hosted with ❤ by GitHub

=gist-end=

Array Methods

LBound와 UBound
배열의 최소 첨자와 최대 첨자를 확인한다.
Dim arr(5)
arr(0) = 10
arr(1) = 20
arr(2) = 30
arr(3) = 40
arr(4) = 50
Debug.Print LBound(arr) & "~" & UBound(arr)  '' 0~4

Split, Join, Filter
Sub array_split()
'Split function: 구분자로 분리될 수 있는 문자열을 분리하여 배열로 만든다.
   ' 구분자(delimiter) comma ','
   Dim a as Variant
   
   a = Split("Red,Blue,Yellow",",")
   
For i = 0 to UBound(a)
  msgbox("Value" & i & " is :"  & a(i))
   Next
End Sub

Sub array_join() 
'Join function: Split 함수의 반대 개념.
' 배열 항목들을 구분하여 문자열을 만든다.
   a = array("Red","Blue","Yellow")

   ' Join using $
   b = join(a,"$")
   msgbox("The Join result after using delimiter is : " & b)
''Red$Blue$Yellow
End Sub

Sub array_filter()
'Filter function: 필터 조건에 맞는 항목만 선택된 배열을 만든다.
   Dim a,b,c,d as Variant
   a = array("Red","Blue","Yellow")
   b = Filter(a,"B")
   c = Filter(a,"e")
   d = Filter(a,"Y")
  
   For each x in b
      msgbox("The Filter result 1: " & x)
   Next
  
   For each y in c
      msgbox("The Filter result 2: " & y)
   Next
  
   For each z in d
      msgbox("The Filter result 3: " & z)
   Next
End Sub
IsArray, Erase
Sub array_erase()
' IsArray function: 배열인지 아닌지 확인(True, False)
   Dim a,b as Variant
   a = array("Red","Blue","Yellow")
   b = "12345"
  
  If IsArray(a) = True then
    Erase a          ' 각 배열의 항목이 초기화 된다.
    ' Dynamic Array인 경우 사용된 메모리가 Free된다.
  End If
   
End Sub






'









No comments:

Post a Comment