데이터 키/항목 쌍을 저장하는 개체입니다.
Dictionary 개체를 사용하기 위해서는 ALT+F11키를 누르고 VBE화면에서 Tools > References에서 Microsoft Scripting Runtime을 참조해야 합니다.
Dictionary 개체 생성 방법
Dictionary 개체를 생성하는 방법은 Early Binding과 Late Binding 2가지가 있습니다.
Early Binding를 사용하기 위해서는 위 그림처럼 참조가 되어 있어야 합니다.
Dim dict As New Dictionary
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
위와 같이 선언했을때 참조가 누락된 경우 아래와 같은 에러가 뜹니다.
참조 라이브러리를 추가하면 IntelliSense(자동 완성 기능)를 통해 개발 시 코드 작성을 도와주고, 코드의 실행 속도가 빨라집니다. 구성원에 익숙하지 않은 저와 같은 초보자는 Early Binding을 하는것이 코딩하기에 편리합니다.
Early and Late Binding - Visual Basic
Learn more about: Early and Late Binding (Visual Basic)
learn.microsoft.com
Late Binding입니다.
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
위 구문에서 "Scripting.Dictionary"는 ProgID를 의미합니다.
ProgID는 "Programmatic Identifier"의 약어로, COM(Component Object Model) 기반 언어에서 COM 객체를 인스턴스화하는 데 사용되는 고유한 식별자입니다. 프로그램이 COM 객체를 인스턴스화하거나 호출하기 위해 사용되는 문자열로, 해당 객체의 클래스 ID(CLSID)와 사용 방법에 대한 정보를 포함합니다.
Late Binding은 참조를 하지 않아도 되지만 library는 등록이 되어 있어야 합니다.
Late Binding을 할 경우에는 IntelliSense(자동 완성 기능)를 사용할 수 없으므로 구성원에 익숙하지 않다면 코딩하는데 어려움을 겪을 수 있습니다.
Late Binding은 참조를 하지 않아도 library가 등록이 되어 있으면 에러가 나지 않으므로 배포할때 Late Binding을 사용합니다.
Add Method
Dictionary 개체에 키와 항목 쌍을 추가합니다.
Syntax
object.Add key, item
object : Dictionary 개체의 이름입니다.
key : 추가되는 항목과 관련된 키입니다.
item : 추가되는 키와 관련된 항목입니다. 키가 이미 있으면 오류가 발생합니다.
문자를 키로 추가
Sub AddToDictionaryExample()
Dim fruits As Scripting.Dictionary
Set fruits = New Scripting.Dictionary ' Dictionary 객체 생성
fruits.Add "apple", 3 ' 새로운 항목 추가: Key = "apple", Item = 3
fruits.Add "banana", 5 ' 새로운 항목 추가: Key = "banana", Item = 5
fruits.Add "orange", 2 ' 새로운 항목 추가: Key = "orange", Item = 2
End Sub
Sub AddToDictionaryExample()
Dim fruits As Scripting.Dictionary
Set fruits = New Scripting.Dictionary ' Dictionary 객체 생성
fruits.Add "apple", 3 ' 새로운 항목 추가: Key = "apple", Item = 3
fruits.Add "banana", 5 ' 새로운 항목 추가: Key = "banana", Item = 5
fruits.Add "apple", 2 ' 키가 이미 있으므로 에러 발생
End Sub
Sub Example1()
Dim myDict As Dictionary
Set myDict = New Dictionary
' 키-값 쌍 추가
myDict.Add "A", 1
myDict.Add "B", 2
myDict.Add "C", 3
' 결과 출력
Debug.Print myDict("A") ' 출력값: 1
Debug.Print myDict("B") ' 출력값: 2
Debug.Print myDict("C") ' 출력값: 3
End Sub
Sub Example2()
Dim myDict As Dictionary
Set myDict = New Dictionary
' 키-값 쌍 추가
myDict.Add "name", "홍길동"
myDict.Add "age", 30
myDict.Add "city", "서울"
' 결과 출력
Debug.Print myDict("name") ' 출력값: 홍길동
Debug.Print myDict("age") ' 출력값: 30
Debug.Print myDict("city") ' 출력값: 서울
End Sub
숫자를 키로 추가
Sub Example3()
Dim myDict As Dictionary
Set myDict = New Dictionary
Dim i As Integer
' 숫자를 키로 사용
For i = 1 To 5
myDict.Add CStr(i), "값" & CStr(i)
Next i
' 결과 출력
For i = 1 To 5
Debug.Print myDict(CStr(i)) ' 출력값: 값1, 값2, 값3, 값4, 값5
Next i
End Sub
Sub DictionaryWithNumberKey()
' 라이브러리 참조를 위해 추가
' Tools -> References -> Microsoft Scripting Runtime
Dim staffId As Variant
Dim staffDict As Scripting.Dictionary
Set staffDict = New Scripting.Dictionary
' 사원번호를 키로 사용하여 사원이름을 저장
With staffDict
.Add 1, "Nancy Davolio"
.Add 2, "Andrew Fuller"
.Add 3, "Janet Leverling"
.Add 4, "Margaret Peacock"
.Add 5, "Steven Buchanan"
.Add 6, "Michael Suyama"
.Add 7, "Robert King"
.Add 8, "Laura Callahan"
.Add 9, "Anne Dodsworth"
End With
' Dictionary를 사용해서 사원번호에 따른 사원이름 출력
For Each staffId In staffDict.Keys
Debug.Print "사원번호: " & staffId & ", 이름: " & staffDict(staffId)
Next staffId
End Sub
날짜를 키로 추가
Sub DictionaryWithDateKey()
' 라이브러리 참조를 위해 추가
' Tools -> References -> Microsoft Scripting Runtime
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
' 날짜를 키로 사용하는 항목 추가
dict.Add #1/1/2023#, "새해"
dict.Add #2/14/2023#, "발렌타인데이"
dict.Add #3/1/2023#, "삼일절"
' Dictionary를 사용해서 날짜에 대한 정보 출력
Dim key As Variant
For Each key In dict.Keys
Debug.Print "날짜: " & CStr(key) & ", 설명: " & dict(key)
Next key
End Sub
배열 요소를 Dictionary의 키와 값으로 추가하기
Sub Example4()
Dim myDict As Dictionary
Set myDict = New Dictionary
Dim fruit As Variant
Dim price As Variant
Dim i As Integer
Dim key As Variant
' 배열로 키와 값 추가
fruit = Array("사과", "바나나", "딸기", "포도", "복숭아")
price = Array(1000, 2000, 3000, 4000, 5000)
' 키-값 쌍 추가
For i = LBound(fruit) To UBound(fruit)
myDict.Add fruit(i), price(i)
Next i
' 결과 출력
For Each key In myDict.Keys
Debug.Print key & ": " & myDict(key)
Next key
End Sub
Dictionary에 배열을 값(Value)으로 추가하기
Sub DictionaryWithArrayValue()
' 라이브러리 참조를 위해 추가
' Tools -> References -> Microsoft Scripting Runtime
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
Dim arr(2) As Integer
arr(0) = 10
arr(1) = 20
arr(2) = 30
dict.Add "Array1", arr ' 배열을 값(Value)로 추가
' 저장된 배열 값을 출력
Dim key As Variant
Dim i As Integer
For Each key In dict.Keys
Debug.Print "키: " & key
For i = LBound(dict(key)) To UBound(dict(key))
Debug.Print "배열 값(" & i & "): " & dict(key)(i)
Next i
Next key
End Sub
여러 배열을 값(Value)으로 갖는 Dictionary 생성하기
Sub DictionaryWithMultipleArrayValues()
' 라이브러리 참조 추가하기
' Tools -> References -> Microsoft Scripting Runtime
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
Dim arr1(2) As Integer
arr1(0) = 10
arr1(1) = 20
arr1(2) = 30
Dim arr2(2) As Integer
arr2(0) = 40
arr2(1) = 50
arr2(2) = 60
' 배열을 값(Value)로 추가
dict.Add "Array1", arr1
dict.Add "Array2", arr2
' 저장된 배열 값 출력
Dim key As Variant
Dim i As Integer
For Each key In dict.Keys
Debug.Print "키: " & key
For i = LBound(dict(key)) To UBound(dict(key))
Debug.Print "배열 값(" & i & "): " & dict(key)(i)
Next i
Debug.Print "--------------"
Next key
End Sub
Dictionary에 다른 Dictionary 값을 추가하기
Sub DictionaryWithDictionaryValue()
' 라이브러리 참조를 위해 추가
' Tools -> References -> Microsoft Scripting Runtime
Dim mainDict As Scripting.Dictionary
Set mainDict = New Scripting.Dictionary
Dim subDict1 As Scripting.Dictionary
Set subDict1 = New Scripting.Dictionary
subDict1.Add "A", 10
subDict1.Add "B", 20
subDict1.Add "C", 30
Dim subDict2 As Scripting.Dictionary
Set subDict2 = New Scripting.Dictionary
subDict2.Add "D", 40
subDict2.Add "E", 50
subDict2.Add "F", 60
mainDict.Add "Dict1", subDict1
mainDict.Add "Dict2", subDict2
' 저장된 Dictionary 값 출력
Dim key As Variant
Dim subKey As Variant
For Each key In mainDict.Keys
Debug.Print "주 키: " & key
For Each subKey In mainDict(key).Keys
Debug.Print " 부 키: " & subKey & ", 값: " & mainDict(key)(subKey)
Next subKey
Debug.Print "------------------"
Next key
End Sub
클래스 개체를 Dictionary의 값(Value)으로 추가하기
'Fruit 클래스 모듈입니다.
Public Name As String
Public Quantity As Integer
Public Price As Double
Public Function GetTotalPrice() As Double
GetTotalPrice = Quantity * Price
End Function
Sub AddClassObjectsToDictionary()
' 라이브러리 참조를 위해 추가
' Tools -> References -> Microsoft Scripting Runtime
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
' 클래스 개체 생성 및 속성 설정
Dim apple As New Fruit
apple.Name = "Apple"
apple.Quantity = 10
apple.Price = 1.5
Dim banana As New Fruit
banana.Name = "Banana"
banana.Quantity = 5
banana.Price = 0.7
' 클래스 개체를 Dictionary에 추가
dict.Add "Apple", apple
dict.Add "Banana", banana
' 저장된 클래스 개체 값 출력
Dim key As Variant
For Each key In dict.Keys
Debug.Print "Fruit: " & dict(key).Name
Debug.Print " Quantity: " & dict(key).Quantity
Debug.Print " Price: " & Format(dict(key).Price, "Currency")
Debug.Print " Total Price: " & Format(dict(key).GetTotalPrice(), "Currency")
Debug.Print "---------------------"
Next key
End Sub
Key property
Dictionary 객체에 키를 설정합니다.
Syntax
object.Key (key) = newkey
object : Dictionary 개체의 이름입니다.
key : 변경되는 키 값입니다.
newkey : 지정된 키를 대체하는 새 값입니다.
단일 키 변경하기
Sub ChangeKey_Example1()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
dict.Add "one", 1
dict.Add "two", 2
dict.Add "three", 3
' 키 변경
dict.key("one") = "first"
' 결과 출력
Debug.Print "Key 'one' changed to 'first':"
Dim k As Variant
For Each k In dict.keys
Debug.Print k, dict(k)
Next k
Set dict = Nothing
End Sub
Dictionary에 저장된 특정 아이템의 키 값을 변경하기
Sub ChangeKeyExample()
' Dictionary 개체 생성
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Dictionary에 아이템 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' 기존 키와 변경할 키 지정
Dim oldKey As Variant
oldKey = "banana"
Dim newKey As Variant
newKey = "grape"
' 특정 아이템의 키 값을 변경
myDict.Key(oldKey) = newKey
' 변경 결과 출력
MsgBox "Key changed from '" & oldKey & "' to '" & newKey & "'."
End Sub
Dictionary의 모든 키를 일괄적으로 변경하기
Sub RenameAllKeysExample()
' Dictionary 개체 생성
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Dictionary에 아이템 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' 변경할 키 값들을 담은 배열
Dim keysToChange() As Variant
keysToChange = Array("apple", "banana", "orange")
' 새로운 키 값들을 담은 배열
Dim newKeys() As Variant
newKeys = Array("red apple", "yellow banana", "sweet orange")
' 모든 아이템의 키 값을 변경
Dim i As Integer
For i = LBound(keysToChange) To UBound(keysToChange)
myDict.key(keysToChange(i)) = newKeys(i)
Next i
' 변경 결과 출력
Debug.Print "All keys changed successfully."
End Sub
Dictionary의 모든 아이템에 10을 더하는 예제
Sub AddTenToValues()
' Dictionary 개체 생성
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Dictionary에 아이템 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' 모든 아이템의 값을 10씩 증가시킴
Dim key As Variant
Dim oldValue As Variant
Dim newValue As Variant
For Each key In myDict.keys
oldValue = myDict.item(key)
newValue = oldValue + 10
myDict.item(key) = newValue
Next key
' 결과 출력
For Each key In myDict.keys
Debug.Print key, myDict.item(key)
Next key
End Sub
키를 대문자로 변경하기
Sub ChangeKey_Example2()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
dict.Add "apple", "Fruit"
dict.Add "banana", "Fruit"
dict.Add "carrot", "Vegetable"
' 키를 대문자로 변경
Dim oldKey As Variant
For Each oldKey In dict.keys
Dim newKey As String
newKey = UCase(oldKey)
If newKey <> oldKey Then
dict.key(oldKey) = newKey
End If
Next oldKey
' 결과 출력
Debug.Print "Keys changed to uppercase:"
Dim k As Variant
For Each k In dict.keys
Debug.Print k, dict(k)
Next k
Set dict = Nothing
End Sub
키에 접두어 붙이기
Sub ChangeKey_Example3()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
dict.Add "UserName", "John"
dict.Add "UserAge", 27
dict.Add "UserCountry", "USA"
' 키에 "user_" 접두어 붙이기
Dim oldKey As Variant
For Each oldKey In dict.keys
Dim newKey As String
newKey = "user_" & oldKey
If newKey <> oldKey Then
dict.key(oldKey) = newKey
End If
Next oldKey
' 결과 출력
Debug.Print "Keys with 'user_' prefix:"
Dim k As Variant
For Each k In dict.keys
Debug.Print k, dict(k)
Next k
Set dict = Nothing
End Sub
Item Property
Dictionary 개체의 지정된 키에 대한 항목을 설정하거나 반환합니다.
Syntax
object.Item (key) [ = newitem ]
object : Dictionary 개체의 이름입니다.
key : 검색 또는 추가할 항목과 연결된 키입니다.
newitem : 지정된 키와 연관된 새 값입니다
Dictionary에서 값을 읽어오기
Sub ReadValueFromDictionary()
Dim myDict As Scripting.Dictionary
Set myDict = New Scripting.Dictionary
' 값을 추가합니다.
myDict.Add "Apple", 100
myDict.Add "Banana", 50
myDict.Add "Orange", 80
' 값을 출력합니다.
Debug.Print "Apple: " & myDict.Item("Apple")
Debug.Print "Banana: " & myDict.Item("Banana")
Debug.Print "Orange: " & myDict.Item("Orange")
End Sub
Dictionary에서 상품 가격 가져오기
Sub GetProductPrices()
Dim prices As Dictionary
Set prices = New Dictionary
prices.Add "ItemA", 20
prices.Add "ItemB", 30
prices.Add "ItemC", 40
' 상품 가격 가져오기
Debug.Print "ItemA 가격: " & prices.Item("ItemA")
Debug.Print "ItemB 가격: " & prices.Item("ItemB")
Debug.Print "ItemC 가격: " & prices.Item("ItemC")
End Sub
Dictionary에서 학생들의 성적 가져오기
Sub GetStudentGrades()
Dim grades As Dictionary
Set grades = New Dictionary
grades.Add "Alice", 85
grades.Add "Bob", 78
grades.Add "Carol", 90
' 학생 성적 가져오기
Debug.Print "Alice 성적: " & grades.Item("Alice")
Debug.Print "Bob 성적: " & grades.Item("Bob")
Debug.Print "Carol 성적: " & grades.Item("Carol")
End Sub
Dictionary에서 국가별 수도 가져오기
Sub GetCountryCapitals()
Dim capitals As Dictionary
Set capitals = New Dictionary
capitals.Add "USA", "Washington, D.C."
capitals.Add "France", "Paris"
capitals.Add "Germany", "Berlin"
' 국가별 수도 가져오기
Debug.Print "USA 수도: " & capitals.Item("USA")
Debug.Print "France 수도: " & capitals.Item("France")
Debug.Print "Germany 수도: " & capitals.Item("Germany")
End Sub
Dictionary에서 키-값 쌍 추가, 값 가져오기 및 수정하기
Sub Example1()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 키-값 쌍을 Dictionary에 추가
dict.Add "Color1", "Red"
dict.Add "Color2", "Green"
dict.Add "Color3", "Blue"
' 값을 가져오기
Debug.Print "Color1: ", dict.Item("Color1") ' 결과: Red
' 값을 수정하기
dict.Item("Color2") = "Yellow"
Debug.Print "Color2: ", dict.Item("Color2") ' 결과: Yellow
End Sub
Dictionary에서 모든 키-값 쌍 순회하여 출력하기
Sub Example2()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 키-값 쌍을 Dictionary에 추가
dict.Add "fruit1", "Apple"
dict.Add "fruit2", "Banana"
dict.Add "fruit3", "Cherry"
' 모든 키-값 쌍 출력
Dim key As Variant
For Each key In dict.Keys
Debug.Print key & ": " & dict.Item(key)
Next
End Sub
Dictionary에서 값을 변경하여 할인율 적용하기
Sub UpdatePricesWithDiscount()
Dim prices As Dictionary
Set prices = New Dictionary
prices.Add "ItemA", 20
prices.Add "ItemB", 30
prices.Add "ItemC", 40
' 할인율 적용
Dim discount As Double
discount = 0.9 ' 10% 할인
Dim key As Variant
For Each key In prices.Keys
' 변경 전 값 출력
Debug.Print key & " 변경 전 가격: " & prices.Item(key)
' 할인 적용
prices.Item(key) = prices.Item(key) * discount
' 변경 후 값 출력
Debug.Print key & " 변경 후 가격: " & prices.Item(key)
Next
End Sub
Dictionary에서 학생들의 성적 업데이트하기
Sub UpdateStudentGrades()
Dim grades As Dictionary
Set grades = New Dictionary
grades.Add "Alice", 85
grades.Add "Bob", 78
grades.Add "Carol", 90
' 5점 추가 적용
Dim points As Integer
points = 5
Dim key As Variant
For Each key In grades.Keys
' 변경 전 성적 출력
Debug.Print key & " 변경 전 성적: " & grades.Item(key)
' 점수 추가
grades.Item(key) = grades.Item(key) + points
' 변경 후 성적 출력
Debug.Print key & " 변경 후 성적: " & grades.Item(key)
Next
End Sub
Dictionary에서 상품 재고 감소시키기
Sub UpdateInventory()
Dim inventory As Dictionary
Set inventory = New Dictionary
inventory.Add "ProductA", 50
inventory.Add "ProductB", 30
inventory.Add "ProductC", 20
' 판매로 인한 재고 감소
Dim sold As Dictionary
Set sold = New Dictionary
sold.Add "ProductA", 5
sold.Add "ProductB", 7
sold.Add "ProductC", 2
Dim key As Variant
For Each key In inventory.Keys
' 변경 전 재고 출력
Debug.Print key & " 변경 전 재고: " & inventory.Item(key)
' 재고 감소
inventory.Item(key) = inventory.Item(key) - sold.Item(key)
' 변경 후 재고 출력
Debug.Print key & " 변경 후 재고: " & inventory.Item(key)
Next
End Sub
문자열 내 문자 빈도 계산하기
Sub Example3()
Dim i As Integer
Dim char As String
Dim inputString As String
Dim key As Variant
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
inputString = "hello world"
For i = 1 To Len(inputString)
char = Mid(inputString, i, 1)
If Not dict.Exists(char) Then
dict.Add char, 1
Else
dict.Item(char) = dict.Item(char) + 1
End If
Next
' 문자 빈도 출력
For Each key In dict.Keys
Debug.Print key & ": " & dict.Item(key)
Next
End Sub
Exists method
지정된 키가 Dictionary 개체에 존재하면 True를 반환하고, 존재하지 않으면 False를 반환합니다.
Syntax
object.Exists (key)
object : 필수입니다. Dictionary 개체의 이름입니다.
key : 필수입니다. Dictionary 개체에서 검색 중인 키 값입니다.
Dictionary에서 키의 존재 확인
Sub Example()
Dim keyExists As Boolean
Dim myDict As Scripting.Dictionary
Set myDict = New Scripting.Dictionary
myDict.Add "apple", 5
myDict.Add "banana", 3
myDict.Add "orange", 8
keyExists = myDict.Exists("banana")
If keyExists Then
Debug.Print "The key 'banana' exists in the dictionary."
Else
Debug.Print "The key 'banana' does not exist in the dictionary."
End If
End Sub
키의 존재 여부 확인
Sub ExistsExample1()
Dim dict As Dictionary
Set dict = New Dictionary
' 키와 값을 추가합니다.
dict.Add "apple", 5
dict.Add "banana", 7
dict.Add "cherry", 3
Debug.Print "apple 키가 존재합니까?: " & dict.Exists("apple") ' True를 반환합니다.
Debug.Print "orange 키가 존재합니까?: " & dict.Exists("orange") ' False를 반환합니다.
End Sub
키가 존재할 경우 값을 업데이트하고, 그렇지 않으면 새 키를 추가
Sub ExistsExample2()
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "apple", 5
' 키가 있는지 확인하고 값 업데이트 또는 추가
If dict.Exists("apple") Then
dict("apple") = 10
Else
dict.Add "apple", 10
End If
Debug.Print "apple 값 : " & dict("apple") ' 10을 반환합니다.
End Sub
특정 키 집합이 사전에 존재하는지 확인
Sub ExistsExample3()
Dim i As Integer
Dim msgText As String
Dim keysToCheck(1 To 3) As String
Dim dict As Dictionary
Set dict = New Dictionary
dict.Add "apple", 5
dict.Add "banana", 7
dict.Add "cherry", 3
keysToCheck(1) = "apple"
keysToCheck(2) = "orange"
keysToCheck(3) = "cherry"
For i = LBound(keysToCheck) To UBound(keysToCheck)
msgText = msgText & keysToCheck(i) & " 키가 존재합니까? : " & dict.Exists(keysToCheck(i)) & vbNewLine
Next i
Debug.Print msgText
End Sub
Count Property
Dictionary 개체의 항목 수가 포함된 Long(긴 정수)을 반환합니다. 읽기 전용입니다.
Syntax
object.Count
Count 예제 - 1
Sub DictionaryExample()
' Dictionary 개체 생성
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Dictionary에 아이템 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' Dictionary에 저장된 아이템의 개수 확인
Dim itemCount As Long
itemCount = myDict.Count
' 결과 출력
Debug.Print "Dictionary에 저장된 아이템의 개수: " & itemCount
End Sub
Count 예제 - 2
Sub PrintDictionaryItemCount()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict("apple") = 3
dict("banana") = 5
dict("orange") = 2
' Dictionary에 저장된 항목의 개수 출력
Debug.Print "Dictionary의 항목 개수: " & dict.count
End Sub
Count 예제 - 3
Sub CountDictionaryItems()
Dim dict As Object, i As Integer
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", "Apple"
dict.Add "B", "Banana"
dict.Add "C", "Cherry"
For i = 1 To dict.count
Debug.Print "이 메시지 박스가 " & i & " 번째로 출력됩니다."
Next i
End Sub
Count 예제 - 4
Sub ProcessDataByItemCount()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 5
dict.Add "B", 10
dict.Add "C", 15
If dict.count >= 3 Then
Debug.Print "Dictionary에 3개 이상의 항목이 저장되어 있습니다."
Else
Debug.Print "Dictionary에 저장된 항목이 3개 미만입니다."
End If
End Sub
Count 예제 - 5
Sub Example5_CalculateAverageWithDictionaryCount()
Dim dict As Object, sum As Double, avg As Double
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 5
dict.Add "B", 10
dict.Add "C", 15
dict.Add "D", 20
sum = Application.WorksheetFunction.sum(dict.Items)
avg = sum / dict.count
Debug.Print "Dictionary 값들의 평균은: " & avg & "입니다."
End Sub
Count 예제 - 6
Sub Example4_DictionaryCountToSetArraySize()
'Dictionary 항목 수를 기준으로 배열 크기 설정하기
Dim dict As Object, arr() As Integer, i As Integer
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 1
dict.Add "B", 2
dict.Add "C", 3
dict.Add "D", 4
ReDim arr(0 To dict.count - 1)
For i = LBound(arr) To UBound(arr)
arr(i) = i + 1
Next i
End Sub
Count 예제 - 7
Sub TestDictionaryCount()
Dim myDictionary As Object
Set myDictionary = CreateObject("Scripting.Dictionary")
'Dictionary에 키와 값을 추가합니다.
myDictionary.Add "A", "Apple"
myDictionary.Add "B", "Banana"
myDictionary.Add "C", "Cherry"
'Dictionary의 Count 속성을 사용하여 항목의 개수를 확인합니다.
Debug.Print "Dictionary의 항목 개수: " & myDictionary.count
'Dictionary에서 키를 사용하여 값을 가져옵니다.
Debug.Print "키 A에 대한 값: " & myDictionary("A")
Debug.Print "키 B에 대한 값: " & myDictionary("B")
'Dictionary의 모든 키와 값을 출력합니다.
Dim key As Variant
For Each key In myDictionary.Keys
Debug.Print "키: " & key & ", 값: " & myDictionary(key)
Next key
End Sub
Count 예제 - 8
Sub CalculateAverage()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Dim total As Double
Dim count As Long
' 사용자로부터 숫자들을 입력받고, Dictionary에 저장
Do
Dim num As Double
num = InputBox("숫자를 입력하세요 (종료하려면 0 입력)", "숫자 입력")
If num = 0 Then Exit Do ' 0을 입력하면 입력 종료
dict.Add "Number" & count, num
total = total + num
count = count + 1
Loop
' 입력된 숫자들의 평균 계산 및 출력
Dim average As Double
If count > 0 Then
average = total / count
Debug.Print "평균: " & average
Else
Debug.Print "입력된 숫자가 없습니다."
End If
' Dictionary에 저장된 항목의 개수 출력
Debug.Print "입력된 숫자의 개수: " & dict.count
End Sub
Keys method
Dictionary 객체에 존재하는 모든 키를 포함하는 배열을 반환합니다.
Syntax
object.Keys
Dictionary의 모든 키 출력
Sub PrintDictionaryKeys()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' 모든 키 출력
Dim key As Variant
For Each key In myDict.Keys
Debug.Print key
Next key
End Sub
Dictionary의 모든 값 출력
Sub PrintDictionaryValues()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' 모든 값 출력
Dim key As Variant
For Each key In myDict.Keys
Debug.Print myDict(key)
Next key
End Sub
키와 값이 모두 충족하는 항목 찾기
Sub FindItemWithKeyAndValue()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' 특정 키와 값이 있는지 검사
Dim searchKey As String
Dim searchValue As Long
searchKey = "apple"
searchValue = 10
Dim found As Boolean
found = False
Dim key As Variant
For Each key In myDict.Keys
If key = searchKey And myDict(key) = searchValue Then
found = True
Exit For
End If
Next key
If found Then
Debug.Print "찾은 항목: 키(" & searchKey & "), 값(" & searchValue & ")"
Else
Debug.Print "항목을 찾을 수 없습니다."
End If
End Sub
Dictionary 키를 퀵정렬로 정렬하고 출력하기
Sub TestQuickSortWithDictionaryKeys()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' 키와 값 추가
myDict.Add "orange", 10
myDict.Add "banana", 5
myDict.Add "apple", 8
' 키 추출 및 퀵정렬 호출
Dim keys() As Variant
keys = myDict.keys
Call QuickSort(keys, LBound(keys), UBound(keys))
' 정렬된 키를 사용하여 Dictionary의 데이터 출력
Dim i As Long
For i = LBound(keys) To UBound(keys)
Debug.Print "키(" & keys(i) & "), 값(" & myDict(keys(i)) & ")"
Next i
End Sub
Sub QuickSort(arr() As Variant, left As Long, right As Long)
Dim i As Long, j As Long
Dim pivot As Variant
Dim temp As Variant
i = left
j = right
pivot = arr((left + right) \ 2)
Do While i <= j
Do While arr(i) < pivot
i = i + 1
Loop
Do While arr(j) > pivot
j = j - 1
Loop
If i <= j Then
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
i = i + 1
j = j - 1
End If
Loop
If left < j Then QuickSort arr, left, j
If i < right Then QuickSort arr, i, right
End Sub
Items method
Dictionary 개체의 모든 항목을 포함하는 배열을 반환합니다.
Syntax
object.Items
Items 예제 - 1
Sub DictionaryItemsExample1()
Dim dict As Object
Dim elem As Variant
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 1
dict.Add "B", 2
dict.Add "C", 3
For Each elem In dict.Items
Debug.Print elem
Next elem
End Sub
Items 예제 - 2
Sub DictionaryItemsExample2()
Dim dict As Object
Dim elem As Variant
Dim searchValue As Variant
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 1
dict.Add "B", 2
dict.Add "C", 3
searchValue = 2
For Each elem In dict.Items
If elem = searchValue Then
Debug.Print "Found value: " & elem
Exit For
End If
Next elem
End Sub
Items 예제 - 3
Sub DictionaryItemsExample3()
Dim dict As Object
Dim i As Integer
Dim keys As Variant
Dim values As Variant
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 1
dict.Add "B", 2
dict.Add "C", 3
keys = dict.keys
values = dict.Items
For i = 0 To dict.count - 1
Debug.Print "Key: " & keys(i) & ", Value: " & values(i)
Next i
End Sub
Items 예제 - 4
Sub SumValues()
' Dictionary 개체 생성
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Dictionary에 아이템 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' Value 합산
Dim total As Double
total = 0
Dim item As Variant
For Each item In myDict.Items
total = total + item
Next item
' 합산 결과 출력
Debug.Print "Total: " & total
End Sub
Items 예제 - 5
Sub ConvertToArrayAndCalculateAverage()
' Dictionary 개체 생성
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Dictionary에 아이템 추가
myDict.Add "apple", 10
myDict.Add "banana", 5
myDict.Add "orange", 8
' Value를 배열로 변환
Dim valuesArr() As Variant
valuesArr = myDict.Items
' 평균 계산
Dim total As Double
Dim count As Integer
total = 0
count = 0
Dim i As Integer
For i = LBound(valuesArr) To UBound(valuesArr)
total = total + valuesArr(i)
count = count + 1
Next i
Dim average As Double
average = total / count
' 결과 출력
Debug.Print "Values Array: " & Join(valuesArr, ", ")
Debug.Print "Average: " & average
End Sub
Items 예제 - 6
Sub DictionaryItemsExample6()
Dim dict As Object
Dim values As Variant
Dim median As Variant
Dim mean As Double, variance As Double, deviation As Double
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "A", 4
dict.Add "B", 2
dict.Add "C", 8
dict.Add "D", 5
values = dict.Items
median = WorksheetFunction.median(values)
mean = WorksheetFunction.average(values)
variance = WorksheetFunction.Var(values, 0)
deviation = WorksheetFunction.StDev(values, 0)
Debug.Print "Median: " & median & ", Mean: " & mean
Debug.Print "Variance: " & variance & ", Deviation: " & deviation
End Sub
Remove method
Dictionary 개체 에서 키/항목 쌍을 제거합니다.
Syntax
object.Remove (key)
object : Dictionary 개체의 이름입니다.
key : Dictionary 개체에서 제거하려는 키/항목 쌍과 연결된 키입니다.
지정된 키/항목 쌍이 존재하지 않으면 오류가 발생합니다.
Remove 예제 - 1
Sub DictionaryRemoveExample()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' Add some items to the dictionary
myDict.Add "Apple", 1
myDict.Add "Banana", 2
myDict.Add "Cherry", 3
' Remove an item from the dictionary
myDict.Remove "Banana"
' Print the remaining items in the dictionary
Dim key As Variant
For Each key In myDict.keys
Debug.Print key & ": " & myDict(key)
Next key
End Sub
Remove 예제 - 2
Sub DictionaryRemoveIfExists()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
' 아이템을 사전에 추가합니다.
myDict.Add "Car", "Toyota"
myDict.Add "Color", "Blue"
' 제거할 키가 사전에 있는지 확인합니다.
Dim keyToRemove As String
keyToRemove = "Color"
If myDict.Exists(keyToRemove) Then
myDict.Remove keyToRemove
Debug.Print keyToRemove & "가(이) 사전에서 제거되었습니다."
Else
Debug.Print keyToRemove & "가(이) 사전에 존재하지 않습니다."
End If
End Sub
Remove 예제 - 3
Sub RemoveSingleKey()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' Dictionary에 키/값 쌍 추가
dict.Add "Key1", "Value1"
dict.Add "Key2", "Value2"
dict.Add "Key3", "Value3"
' 단일 키("Key2") 삭제
dict.Remove "Key2"
End Sub
Remove 예제 - 4
Sub RemoveMultipleKeys()
Dim dict As Object, keysToDelete() As Variant, i As Long
Set dict = CreateObject("Scripting.Dictionary")
' Dictionary에 키/값 쌍 추가
dict.Add "Key1", "Value1"
dict.Add "Key2", "Value2"
dict.Add "Key3", "Value3"
' 삭제할 키들의 배열
keysToDelete = Array("Key1", "Key3")
' 키를 순차적으로 삭제
For i = LBound(keysToDelete) To UBound(keysToDelete)
dict.Remove keysToDelete(i)
Next i
End Sub
RemoveAll method
Dictionary 개체에서 모든 키, 항목 쌍을 제거합니다.
RemoveAll 예제
Sub RemoveAllExample()
Dim myDict As Object
Set myDict = CreateObject("Scripting.Dictionary")
myDict.Add "A", "Apple"
myDict.Add "B", "Banana"
myDict.Add "C", "Cherry"
' RemoveAll 메서드를 사용하여 Dictionary의 모든 항목 삭제
myDict.RemoveAll
' 딕셔너리가 비어있는지 확인
Debug.Print "딕셔너리의 항목 수: " & myDict.count
End Sub
CompareMode property
Dictionary 개체의 문자열 키를 비교하기 위한 비교 모드를 설정하고 반환합니다.
Syntax
object.CompareMode [ = compare ]
object : 필수입니다. Dictionary 개체의 이름입니다.
Compare : 선택 사항입니다. 제공된 경우 비교는 StrComp와 같은 함수에서 사용하는 비교 모드를 나타내는 값입니다.
비교 모드는 vbBinaryCompare와 vbTextCompare가 있습니다.
vbBinaryCompare : 이진 비교를 수행합니다.(대/소문자 구분)
vbTextCompare : 텍스트 비교를 수행합니다.(대/소문자 무시)
StrComp함수는 아래 링크를 참고하세요.
StrComp 함수
문자열 비교 결과를 나타내는 Variant(Integer)를 반환합니다. 구문은 다음과 같습니다. Syntax StrComp(string1, string2, [ compare ]) string1 : 필수입니다. 유효한 문자열 표현식입니다. string2 : 필수입니다. 유
vbaplayground.tistory.com
vbBinaryCompare 예제 - 1
Sub CaseSensitiveNameList()
Dim nameList As Object
Set nameList = CreateObject("Scripting.Dictionary")
' CompareMode 속성 설정 (vbBinaryCompare: 대소문자 구분)
nameList.CompareMode = vbBinaryCompare
' 이름 추가
nameList.Add "John", "John Doe"
nameList.Add "john", "Another John"
nameList.Add "Jane", "Jane Smith"
' 대소문자 구분하여 이름 조회
MsgBox "Name: John - Value: " & nameList("John") & vbCrLf & _
"Name: john - Value: " & nameList("john") & vbCrLf & _
"Name: Jane - Value: " & nameList("Jane")
' Dictionary 삭제
Set nameList = Nothing
End Sub
CompareMode를 변경하면 아래와 같이 에러가 납니다.
vbBinaryCompare 예제 - 2
Sub BinaryCompareWithExists()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' CompareMode 속성 설정 (vbBinaryCompare: 대소문자 구분)
dict.CompareMode = vbBinaryCompare
' Dictionary에 값 추가
dict.Add "apple", "사과"
dict.Add "APPLE", "사과 (대문자)"
dict.Add "banana", "바나나"
' 대소문자를 구분하여 키가 존재하는지 확인 (Exists 메서드 사용)
Dim keyToCheck As String
keyToCheck = "Apple"
If dict.Exists(keyToCheck) Then
Debug.Print keyToCheck & " 키가 존재합니다. 값: " & dict(keyToCheck)
Else
Debug.Print keyToCheck & " 키가 존재하지 않습니다."
End If
' Dictionary 삭제
Set dict = Nothing
End Sub
vbBinaryCompare 예제 - 3
Sub BinaryCompareWithExists()
' Microsoft Scripting Runtime 참조 설정 필요
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
' CompareMode를 vbBinaryCompare로 설정
dict.CompareMode = vbBinaryCompare
' Dictionary에 key-value 페어 추가
dict.Add "apple", 5
dict.Add "BANANA", 10
dict.Add "Cherry", 15
' Dictionary에서 키 검색 (대소문자 구분)
If dict.Exists("banana") Then
Debug.Print "banana 키가 존재합니다: " & dict("banana")
Else
Debug.Print "키가 존재하지 않습니다."
End If
If dict.Exists("BANANA") Then
Debug.Print "BANANA 키가 존재합니다: " & dict("BANANA")
Else
Debug.Print "키가 존재하지 않습니다."
End If
End Sub
vbTextCompare 예제 - 1
Sub TextCompareExample()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' CompareMode 속성 설정 (vbTextCompare: 대소문자 무시)
dict.CompareMode = vbTextCompare
' Dictionary에 값 추가 (대소문자가 다른 문자열을 키로 사용)
dict.Add "apple", "사과"
dict.Add "banana", "바나나"
dict.Add "grape", "포도"
' 대소문자를 무시하여 키가 존재하는지 확인 (Exists 메서드 사용)
Dim keyToCheck As String
keyToCheck = "ApPle"
If dict.Exists(keyToCheck) Then
Debug.Print keyToCheck & " 키가 존재합니다. 값: " & dict(keyToCheck)
Else
Debug.Print keyToCheck & " 키가 존재하지 않습니다."
End If
' Dictionary 삭제
Set dict = Nothing
End Sub
vbTextCompare 예제 - 2
Sub DictionaryWithTextCompare()
' Microsoft Scripting Runtime 참조 설정 필요
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
' CompareMode를 vbTextCompare로 설정
dict.CompareMode = vbTextCompare
' Dictionary에 key-value 페어 추가
dict.Add "apple", 5
dict.Add "BANANA", 10
dict.Add "Cherry", 15
' Dictionary에서 키 검색 (대소문자 구분 없음)
If dict.Exists("banana") Then
Debug.Print "banana 키가 존재합니다: " & dict("banana")
Else
Debug.Print "키가 존재하지 않습니다."
End If
If dict.Exists("Banana") Then
Debug.Print "Banana 키가 존재합니다: " & dict("Banana")
Else
Debug.Print "키가 존재하지 않습니다."
End If
End Sub
'Microsoft Scripting Runtime' 카테고리의 다른 글
Folder 개체 (0) | 2023.08.10 |
---|---|
Folders 컬렉션 (0) | 2023.08.10 |
Drive 개체 (0) | 2023.08.10 |
Drives 컬렉션 (0) | 2023.08.09 |
FileSystemObject 개체 (0) | 2023.07.30 |