2019-01-04

VBA - Basics

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


2. Procedure
프로시져는 한번에 실행될 명령의 모음이다. 엑셀에게 특정한 작업을 수행하도록 지시한다.
단순한 프로시져부터 복잡한 프로시져까지 만들 수 있지만, 복잡한 것은 작게 나누어 작성하여 유지보수를 쉽게 하는 것이 좋다.
함수의 코드는 Sub 과 End Sub 사이에 위치한다.
https://gist.github.com/SeongilRyu/6c541219ca325bef40cb9401c37b0edb



3. Function
펑션, 함수는 재사용 가능한 코드의 모음이다., 프로그램의 어디에서든지 호출 가능하며 리턴되는 값이 있다. 
기본으로 엑셀에 포함된 함수외에, VBA로 사용자 정의 함수를 만들 수 있다.
함수의 코드는 Function 과 End Function 사이에 위치한다.
https://gist.github.com/SeongilRyu/ec60bd70f8e9b3dc0aa3d106b5c070d4


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은 일련의 문자열이다. 알파벳, 숫자, 특수문자로 구성된다. 변수에 담기는 스트링은 겹따옴표( " ")로 표현한다.


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

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

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

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


ReDim

초기에는 배열의 크기를 지정하지 않고 나중에 사용될 때 크기를 지정할때 ReDim을 사용한다.
=gist=

=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