반응형

모든 절차를 수행하기 전에 각 모듈 시트의 맨 위에 모듈 수준 선언 Option Explicit를 입력하는 것이 좋습니다. Option Explicit은 다음을 수행합니다.
Dim 문을 사용하여 모든 변수를 선언합니다. 선언되지 않은 변수는 컴파일 시간에 오류를 생성합니다.

 

 

이유를 알고 싶다.

 

드디어 오늘 알게되었다.

 

Option Explicit라고 선언을 하면

아래에 있는 모든 내용에 대해

'정의하지 않는 변수가 있으면 오류를 발생시킨다.

 

반응형

'VBA' 카테고리의 다른 글

매크로 단축키 설정 방법  (0) 2022.02.17
화씨를 썹시로 바꾸는 함수  (0) 2022.02.17
숫자 양식을 지수형식으로 설정하기  (0) 2022.02.17
반복문(for...next, do while ...loop)  (0) 2022.02.17
if문  (0) 2022.02.17
반응형

숫자 양식을 지수형식으로 설정하기

Sub ScientificFormat()
'
'ScientificFormat Macro
'Keyboard shortcut: Ctrl+e
Selection.NumberFormat = "0.00E+00"
End Sub
반응형
반응형

반복문(for...next, do while ...loop)에 대해 알아보자

개발도구 > 삽입 > ActiveX 컨트롤 > command button을 삽입한다.

 

command button을 더블 클릭하면 VBA editor로 넘어 간다.

 

단순 반복문

아래 코드는 A1셀에서 A6셀까지 숫자 100을 입력한다.

Dim i As Integer

For i = 1 To 6
 Cells(i, 1).Value = 100
Next i

여기서 맨마지막 next 다음의 i는 생략 가능하다.

단순반복문

 

 

2중 반복문

아래 코드는 A1:B6에 숫자 100을 입력한다.

Dim i As Integer, j As Integer

For i = 1 To 6
    For j = 1 To 2
        Cells(i, j).Value = 100
    Next j
Next i

2중 반복문

 

 

3중 반복문

 

이 명령을 사용하기 전에 엑셀의 워크시트가 최소 3개가 있어야 한다.

Dim c As Integer, i As Integer, j As Integer

For c = 1 To 3
    For i = 1 To 6
        For j = 1 To 2
            Worksheets(c).Cells(i, j).Value = 100
        Next j
    Next i
Next c

worksheets(1)은 엑셀에서 왼쪽에서 첫번째 워크시트를 의미한다.

워크시트의 순서가 바뀌면 내가 원하는 워크시트에 원하는 결과를 얻을 수 없다.

 

 

Do While .... Loop

Dim i As Integer
i = 1

Do While i < 6
    Cells(i, 1).Value = 20
    i = i + 1
Loop

A1:A5까지 20을 입력하는 기능이다.

 

반복문.xlsm
0.02MB

반응형
반응형

if문

 

아래 if문은 A1셀에 값이 60이상이면 B1셀에 pass를 입력하는 것이다.

A1셀이 60미만이면 B1은 변화가 없다.

 Dim score As Integer, result As String
 
 score = Range("a1").Value
 
 If score >= 60 Then result = "pass"
 
 Range("b1").Value = result

 

if then else를 통해 거짓일때 실행하는 문구를 추가할 수 있다.

A1셀 값이 60이상이면 B1셀에 pass를

A1셀 값이 60미만이면 B1셀에 fail을 입력한다.

 Dim score As Integer, result As String
 
 score = Range("a1").Value
 
 If score >= 60 Then
    result = "pass"
 Else
    result = "fail"
 End If
 
 Range("b1").Value = result

if문.xlsm
0.02MB

반응형
반응형

Excel에서 특정 셀이 변경될 때 매크로 실행

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$1" Then
        Call Mymacro
    End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:B100")) Is Nothing Then
Call Mymacro
End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("A1:C10")

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

' Display a message when one of the designated cells has been 
        ' changed.
        ' Place your code here.
        MsgBox "Cell " & Target.Address & " has changed."

End If
End Sub

 

반응형
반응형

VBA's Built-in Data Types

 

Data Type Storage Required Range of Values
Boolean (Logical) 2 bytes True or False
Integer 2 bytes -32,768 to 32,767
Long integer 4 bytes -2,147,483,648 to 2,147,483,647
Single precision 4 bytes -3.402823E+38 to -1.401298E-45
for negative values; 1.401298E-45
to 3.402823E+38 for positive
values
Double precision 8 bytes -1.797693 13486232E+308 to
-4.9406564584 1247E-324 
for negative values;
4.94065645841247E-324 to
1.797693 13486232E+308 
for positive values
-922,337,203,685,477.5808 to
922,337,203,685,477.5807
Currency 8 bytes
Date 8 bytes Any Object reference
Object 4 bytes
String 1 byte character
Variant 16 bytes
+ 1 byte/character
Any numeric value up to the
range of a Double or anv text
반응형
반응형

Address  Returns the reference of a cell or range, as text.

 


Columns  Returns a Range object that represents a single column or multiple columns.

 


ConvertFormula  Converts cell references in a formula between A1 and R1 C l-style, and between relative and absolute.

 


Evaluate  Converts a formula to a value.

 


Intersect Returns the reference that is the intersection of two ranges.

 


Rows  Returns a Range object that represents a single row or multiple rows.

 


Volatile  Marks a user-defined function as volatile. The function recalculates whenever calculation occurs in any cell of the worksheet.

 

 

반응형

'VBA' 카테고리의 다른 글

Excel에서 특정 셀이 변경될 때 매크로 실행  (0) 2022.01.23
VBA's Built-in Data Types  (0) 2021.12.29
VBA Information 함수 일부  (0) 2021.12.29
VBA text함수 일부  (0) 2021.12.29
VBA 수학 함수 일부  (0) 2021.12.29
반응형

VBA Information 함수 일부

 

IsArray  Returns True if the variable is an array.

 

IsDate Returns True if the expression is a date.

 

IsEmpty Returns True if the variable is uninitialized.

 

IsError Returns True if the expression returns an error.

 

IsMissing Returns True if an optional value has not been passed to a Function procedure.

 

IsNull  Returns True if the expression is null (i.e., contains no valid data).

 

IsNumeric Returns True if the expression can be evaluated to a number.

 

Isobject  Returns True if the expression references a valid object.

 

LBound Returns the lower limit of an array dimension.

 

UBound Returns the upper limit of an array dimension.

 

 

 

반응형
반응형

VBA text함수 일부

 

 

Asc 문자의 ASCII code를 반환한다.

 

Chr ASCII code에 해당하는 문자를 반환한다.

 

Format  기본 제공 또는 사용자 정의에 따라 숫자 형식 지정 숫자 형식 표현. 결과는 문자열입니다.

 

lnstr  문자열 내에서 부분 문자열의 첫 번째 발생을 반환합니다. Excel의 FIND 워크시트 기능과 유사합니다.

 

Len 문자열의 길이(문자 수)를 반환합니다.

 

Left 문자열의 가장 왼쪽 문자를 반환합니다.

 

Right 문자열의 가장 오른쪽 문자를 반환합니다.

 

Mid 문자열에서 지정된 수의 문자를 반환합니다.

 

LTrim 선행 공백이 없는 문자열을 반환합니다.

 

RTrim 후행 공백이 없는 문자열을 반환합니다.

 

Trim 선행 또는 후행 공백 없이 문자열을 반환합니다.

 

Str 숫자를 문자열로 변환합니다. 선행 공간이 예약되어 있습니다.
숫자의 표시를 위해; 숫자가 양수이면 문자열에는 선행 공백이 포함됩니다.

 

LCase  문자열을 소문자로 변환합니다.

 


UCase 문자열을 대문자로 변환합니다.

 

 

반응형
반응형

VBA 수학 함수 일부

 

Abs  절대값을 반환한다.

 

Atn  arctangent값을 반환한다. 결과는 radians이다.

 

Cos cosine값을 반환한다. 결과는 radians이다.

 

EXP  e의 거듭제곱을 반환한다.

 

Int 숫자의 정수부를 반환한다.(rounds down)

 

Log 자연로그 값을 반환한다.

 

Rnd 0보다 크고 1보다 작은 난수를 반환한다.

 

Sin sine값을 반환한다. 결과는 radians이다.

 

Sqr root값을 반환한다.

 

Tan tangent값을 반환한다. 결과는 radians이다.

 

 

반응형

+ Recent posts