**Giới thiệu thư viện COM Dictionary – DictHelper.dll** (1 người xem)

Liên hệ QC

Người dùng đang xem chủ đề này

Tôi tuân thủ nội quy khi đăng bài

phuongnam366377

Thành viên thường trực
Tham gia
25/10/19
Bài viết
213
Được thích
223
**Giới thiệu thư viện COM Dictionary – DictHelper.dll**


DictHelper.dll là một thư viện COM do Kieu Manh phát triển bằng Embarcadero C++ Builder, kế thừa trực tiếp từ lớp TDictionary<TKey, TValue> trong System.Generics.Collections của Delphi. Thư viện này cung cấp một đối tượng Dictionary mạnh mẽ, cho phép lưu trữ và thao tác dữ liệu theo cặp key–value một cách trực quan, hiệu quả và tương thích hoàn toàn với VBA, Excel, VBScript và các ứng dụng COM-based khác.

Tác giả: Kieu Manh + ChatGPT trợ giúp viết mã và viết bài

DictHelper được xây dựng trên nền tảng Delphi Runtime Library (RTL), tận dụng sức mạnh của Generics Collections – một phần không thể thiếu của Delphi hiện đại. Việc kế thừa từ TDictionary giúp đảm bảo hiệu năng cao, quản lý bộ nhớ tối ưu, và hỗ trợ đầy đủ các thao tác cơ bản và nâng cao của Dictionary. Xin trân trọng cảm ơn các kỹ sư Delphi đã xây dựng nên nền tảng tuyệt vời này.

**Tính năng nổi bật:**

– Tương thích hoàn toàn với VBA và Excel
– Hỗ trợ cú pháp For Each để duyệt dữ liệu
– Lưu trữ dữ liệu động với kiểu Variant
– Dễ dàng tích hợp vào macro, automation, hoặc ứng dụng COM

**Các phương thức và thuộc tính hỗ trợ:**

1. Add(key, value): Thêm một cặp key–value vào dictionary. Nếu key đã tồn tại, giá trị sẽ được cập nhật.
2. GetItem(key): Truy xuất giá trị tương ứng với key đã cho.
3. Remove(key): Xóa một key và giá trị tương ứng khỏi dictionary.
4. Exists(key): Kiểm tra xem key có tồn tại trong dictionary hay không. Trả về True hoặc False.
5. Count: Trả về tổng số phần tử hiện có trong dictionary.
6. Item(key): Truy xuất hoặc gán giá trị trực tiếp bằng cú pháp dict(key) = value.
7. Hỗ trợ For Each trong VBA để duyệt qua tất cả các key.

**Ví dụ sử dụng trong VBA:**
Mã:
Sub DemoDictHelper()
 Dim dict As Object
 Set dict = CreateObject("DictHelper.Dictionary")

 dict.Add "Name", "Kieu"
 dict.Add "City", "Lai Thieu"

 If dict.Exists("Name") Then
  MsgBox "Tên: " & dict.GetItem("Name")
 End If

 Debug.Print "Tổng số phần tử: " & dict.Count

 Dim key As Variant
 For Each key In dict
  Debug.Print key & " = " & dict(key)
 Next
End Sub
**Cài đặt và đăng ký:**

– Copy DictHelper.dll vào thư mục hệ thống hoặc thư mục dự án
– Đăng ký DLL bằng lệnh: regsvr32 DictHelper.dll
– Sử dụng CreateObject("DictHelper.Dictionary") trong VBA để khởi tạo đối tượng

**Ứng dụng thực tế:**

– Lọc dữ liệu trùng lặp trong Excel
– Thống kê tần suất xuất hiện
– Tạo bảng ánh xạ key–value động
– Tích hợp vào quy trình automation hoặc báo cáo

DictHelper không chỉ là một thư viện tiện ích – nó là cầu nối giữa sức mạnh của Delphi và sự linh hoạt của VBA. Nếu bạn là lập trình viên Excel, người dùng VBScript, hoặc đang tìm giải pháp lưu trữ dữ liệu linh hoạt trong COM, DictHelper.dll là một lựa chọn đáng tin cậy và dễ triển khai.

---
Thong thả và thư giản khi có gió giới thiệu lên Github + ví dụ sử dụng và DLL sau
 
Chuyển lên kho lưu trữ ai quan tâm có thể sử dụng Free với bất kỳ mục đích nào tùy thích ???!!!

Thư viện **DictHelper.dll** mô phỏng theo `Scripting.Dictionary` của Microsoft, nên:

- **Giao diện sử dụng trong VBE (Visual Basic Editor)** của Excel sẽ rất quen thuộc với người dùng VBA.
- Các phương thức như `Add`, `Exists`, `Remove`, `Item`, `Count`, và hỗ trợ `For Each` đều **giống hệt về cách gọi và cú pháp** như `Scripting.Dictionary`.
- Người dùng VBA có thể **chuyển đổi sang DictHelper mà không cần thay đổi logic code**, chỉ cần thay `CreateObject("Scripting.Dictionary")` thành `CreateObject("DictHelper.Dictionary")`.

---

### ✅ Ví dụ so sánh

**Scripting.Dictionary:**

Mã:
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "Name", "Kieu"
MsgBox dict("Name")

**DictHelper.Dictionary:**

Mã:
Set dict = CreateObject("DictHelper.Dictionary")
dict.Add "Name", "Kieu"
MsgBox dict("Name")

➡️ Kết quả và cú pháp hoàn toàn giống nhau.

1759504900246.png

Giao diện sử dụng trong VBE (Visual Basic Editor) của Excel sẽ rất quen thuộc với người dùng VBA.

1759503883398.png

Ví dụ sử dụng 1

Mã:
Sub Test_DictHelper()
    Dim dict As Object, key
    Set dict = CreateObject("DictHelper.Dictionary")
 
    dict.Add "Name", "Kieu"
    dict.Add "City", "Lai Thieu"
 
    For Each key In dict '' Lôi 458
        Debug.Print key & " = " & dict(key)
    Next
End Sub


Sub TestUniqueFilter()
    Dim dict As Object
    Dim names As Variant
    Dim name As Variant
    Dim key As Variant

    ' Tao doi tuong Dictionary COM
    Set dict = CreateObject("DictHelper.Dictionary")

    ' Mang du lieu co trung lap
    names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan")

    ' Loc duy nhat
    For Each name In names
        If Not dict.Exists(name) Then
            dict.Add name, True
        End If
    Next

    ' In ra danh sach duy nhat
    Debug.Print "Danh sach ten duy nhat:"
    For Each key In dict
        Debug.Print key
    Next
End Sub

Sub TestDuplicateNames()
    Dim dict As Object
    Dim names As Variant
    Dim name As Variant
    Dim key As Variant

    Set dict = CreateObject("DictHelper.Dictionary")

    names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan", "Lan")

    ' Dem so lan xuat hien
    For Each name In names
        If dict.Exists(name) Then
            dict.Add name, dict.GetItem(name) + 1
        Else
            dict.Add name, 1
        End If
    Next

    ' In ra nhung ten xuat hien nhieu hon 1 lan
    Debug.Print "Nhung ten trung lap:"
    For Each key In dict
        If dict.GetItem(key) > 1 Then
            Debug.Print key & " xuat hien " & dict.GetItem(key) & " lan"
        End If
    Next
End Sub

Ví dụ sử dụng 2
Mã:
' Tao doi tuong Dictionary COM
Private Function CreateDict() As Object
    Set CreateDict = CreateObject("DictHelper.Dictionary")
End Function

' 1. Duyet bang For Each (co ban)
Public Sub TraverseForEach()
    Dim dict As Object, key As Variant
    Set dict = CreateDict()
    dict.Add "Name", "Kieu"
    dict.Add "City", "Lai Thieu"

    Debug.Print "Duyet bang For Each:"
    For Each key In dict
        Debug.Print key & " = " & dict.GetItem(key)
    Next
End Sub

' 2. Duyet bang mang tam chua key
Public Sub TraverseByArray()
    Dim dict As Object, keys() As Variant, i As Long
    Set dict = CreateDict()
    dict.Add "Name", "Kieu"
    dict.Add "City", "Lai Thieu"
    dict.Add "Country", "Vietnam"

    ReDim keys(dict.Count - 1)
    i = 0
    Dim key As Variant
    For Each key In dict
        keys(i) = key
        i = i + 1
    Next

    Debug.Print "Duyet bang mang tam:"
    For i = LBound(keys) To UBound(keys)
        Debug.Print keys(i) & " = " & dict.GetItem(keys(i))
    Next
End Sub

' 3. Duyet co dieu kien loc
Public Sub TraverseWithFilter()
    Dim dict As Object, key As Variant
    Set dict = CreateDict()
    dict.Add "Kieu", 3
    dict.Add "Lan", 1
    dict.Add "Hoa", 2

    Debug.Print "Chi in ten xuat hien > 1 lan:"
    For Each key In dict
        If dict.GetItem(key) > 1 Then
            Debug.Print key & " = " & dict.GetItem(key)
        End If
    Next
End Sub

' 4. Duyet nguoc (neu co mang key)
Public Sub TraverseReverse()
    Dim dict As Object, keys() As Variant, i As Long
    Set dict = CreateDict()
    dict.Add "A", 1
    dict.Add "B", 2
    dict.Add "C", 3

    ReDim keys(dict.Count - 1)
    i = 0
    Dim key As Variant
    For Each key In dict
        keys(i) = key
        i = i + 1
    Next

    Debug.Print "Duyet nguoc:"
    For i = UBound(keys) To LBound(keys) Step -1
        Debug.Print keys(i) & " = " & dict.GetItem(keys(i))
    Next
End Sub

' 5. Duyet theo nhom (vi du nhom theo chu cai dau)
Public Sub TraverseGrouped()
    Dim dict As Object, groupDict As Object, key As Variant, firstChar As String
    Set dict = CreateDict()
    Set groupDict = CreateDict()

    dict.Add "Kieu", 1
    dict.Add "Lan", 1
    dict.Add "Linh", 1
    dict.Add "Hoa", 1
    dict.Add "Hanh", 1

    For Each key In dict
        firstChar = Left(key, 1)
        If groupDict.Exists(firstChar) Then
            groupDict.Add firstChar, groupDict.GetItem(firstChar) + 1
        Else
            groupDict.Add firstChar, 1
        End If
    Next

    Debug.Print "Nhom theo chu cai dau:"
    For Each key In groupDict
        Debug.Print key & " co " & groupDict.GetItem(key) & " ten"
    Next
End Sub
File úp lên Github bao gồm nhiều ví dụ mẫu và DLL 32 và 64 bít kèm theo


Downloads
 
Lần chỉnh sửa cuối:
Mới bổ sung thêm 4 hàm mới mô phỏng cho đủ bộ luôn ... chơi vài ngày xong cập nhật lại lên github

Giao diện sử dụng trong VBE (Visual Basic Editor) của Excel sẽ rất quen thuộc với người dùng VBA.

1759546019397.png
1/ Property CompareMode
Mã:
Property CompareMode As Long
    Member of DictHelper.Dictionary
    Gets or sets the string comparison mode (0 = BinaryCompare, 1 = TextCompare).

2/ Keys
Mã:
Function Keys()
    Member of DictHelper.Dictionary
    Returns an array containing all keys in the dictionary, in insertion order.

3/ RemoveAll
Mã:
Sub RemoveAll()
    Member of DictHelper.Dictionary
    Removes all key-value pairs from the dictionary.

4/ SetItem
Mã:
Sub SetItem(Key As String, Value As Long)
    Member of DictHelper.Dictionary
    Sets or updates the value of a specified key using a long integer.
Cách sử dụng Hàm SetItem sẽ như sau

Mã:
Sub Test_SetItem()
    Dim dict As Object
    Set dict = CreateObject("DictHelper.Dictionary")

    ' Them du lieu ban dau
    dict.Add "Name", "Kieu"
    dict.Add "City", "Lai Thieu"

    ' Gan gia tri moi cho key da ton tai
    dict.SetItem "City", 12345

    ' Gan gia tri cho key chua ton tai
    dict.SetItem "Country", 67890

    ' Kiem tra ket qua
    Debug.Print "City = " & dict.Item("City")
    Debug.Print "Country = " & dict.Item("Country")
    'Ket qua:
    'City = 12345
    'Country = 67890

End Sub
 
chủ đề này đã hoàn thiện theo ý tưởng thuyết kế của nó link sau bài số 17

đã cập nhật các phương thức và thuộc tính còn lại như mô tả bài Số 3 và viết chơi thêm vài hàm tùy chỉnh cho VBA ...

Giao diện sử dụng trong VBE (Visual Basic Editor) của Excel sẽ rất quen thuộc với người dùng VBA.

1759636287221.png
1/ hàm

Mã:
Function FilterByKey(Prefix As String) As Dictionary
    Member of DictHelper.Dictionary
    Returns a new dictionary containing items with keys that start with the given prefix.

2/ Hàm

Mã:
Function FilterByValue(Min, Max) As Dictionary
    Member of DictHelper.Dictionary
    Returns a new dictionary containing items with values between Min and Max.

3/ hàm

Mã:
Sub SortByValue([Direction])
    Member of DictHelper.Dictionary
    Sorts dictionary entries by value. Optional Direction: ASC (default) or DESC.

4/ Hàm

Mã:
Sub SortByKey([Direction])
    Member of DictHelper.Dictionary
    Sorts dictionary entries by key. Optional Direction: ASC (default) or DESC.

5/ hàm

Mã:
Sub SortCustom([pCustomOrder])
    Member of DictHelper.Dictionary
    Sorts dictionary keys by an optional custom array; if omitted, keeps current order; if empty, resets to default.

6/ hàm

Mã:
Function ToArray()
    Member of DictHelper.Dictionary
    Returns all key/value pairs as a 2D array.

7/ Hàm

Mã:
Function KeyAt(Index As Long) As String
    Member of DictHelper.Dictionary
    Returns the key at the specified index.
8/ Hàm

Mã:
Function Clone() As Dictionary
    Member of DictHelper.Dictionary
    Returns a deep copy of the current dictionary.

9/ hàm

Mã:
Sub Merge(Other As Dictionary)
    Member of DictHelper.Dictionary
    Merges all key-value pairs from another dictionary into the current one, overwriting duplicates and preserving key order.

Các ví dụ sử dụng mẫu có sẳn trên Github kèm DLL 32 và 64 bit - COM C++ Builder

Khép lại chủ đề này nó đã hoàn thành tôn chỉ và mục đích ban đầu đề ra ...
viết nhanh có chút buổi sáng uống hết ly cafe hình thành khung cho chủ đề này

Downloads

Viết dự Án C++ builder mới
 
Lần chỉnh sửa cuối:

Bài viết mới nhất

Back
Top Bottom