COM DLL `ScriptHelper.RegExp` – Thay thế VBScript.RegExp trong VBA (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
1/ Nội dụng bài Viết do ChatGPT biên soạn theo ý của tôi chỉ huy nó

2/ Code viết trên Delphi 13 + ChatGPT hổ trợ tạo nên thư viện này

3/ là bản thử nghiệm nên phát sinh lỗi là điều đương nhiên ...
Nên quá trình sử dụng có lỗi mô tả chi tiết nếu khả năng có thể Tôi sẽ điều chỉnh viết lại



# COM DLL `ScriptHelper.RegExp` – Thay thế VBScript.RegExp trong VBA

Microsoft đã loại bỏ **VBScript.RegExp** (trong `vbscript.dll`) trên Windows mới, khiến nhiều macro VBA cũ bị lỗi.
Giải pháp: **COM DLL `ScriptHelper.RegExp`** viết bằng Delphi, có thể đăng ký vào Windows và sử dụng trực tiếp trong VBA/Excel/Access/Word.

---

## Cài đặt

1. Copy file `ScriptHelper.dll` vào thư mục tùy ý.
2. Đăng ký bằng lệnh (chạy CMD với quyền admin):

Mã:
   regsvr32 ScriptHelper.dll

3. Trong VBA, tạo đối tượng như sau:
Mã:
   Dim re As Object
   Set re = CreateObject("ScriptHelper.RegExp")

---

## ‍ Ví dụ sử dụng

### 1. Execute – tìm tất cả match

Mã:
Sub TestRegExp()
Dim re As Object, m As Variant

Set re = CreateObject("ScriptHelper.RegExp")
re.Pattern = "123.+?abc.+?@@@"
re.Global = True
re.IgnoreCase = False

m = re.Execute("123  abc  @@@")

Debug.Print "Match count: "; UBound(m) - LBound(m) + 1
Debug.Print "First Match: "; m(0)
```

End Sub

Kết quả:

```
Match count: 1
First Match: 123 abc @@@
```

---

### 2. Replace – thay thế toàn bộ

Mã:
Sub TestReplace()
Dim re As Object, result As Variant

```
Set re = CreateObject("ScriptHelper.RegExp")
re.Pattern = "\d+"
re.Global = True

result = re.Replace("Số 123 và 456", "###")
Debug.Print result   ' Kết quả: Số ### và ###
```

End Sub

---

### 3. FirstMatch – tìm match đầu tiên

Mã:
Sub TestFirstMatch()
Dim re As Object, first As Variant

```
Set re = CreateObject("ScriptHelper.RegExp")
re.Pattern = "\w+"
re.Global = True

first = re.FirstMatch("Xin chao cac ban")
Debug.Print first   ' Kết quả: Xin
```

End Sub

---

### 4. Split – tách chuỗi theo Regex

Mã:
Sub TestSplit()
Dim re As Object, parts As Variant, i As Long

```
Set re = CreateObject("ScriptHelper.RegExp")
re.Pattern = "[,; ]+"

parts = re.Split("A,B;C D")

For i = LBound(parts) To UBound(parts)
    Debug.Print parts(i)
Next
' Kết quả:
' A
' B
' C
' D
```

End Sub

---

## ✅ Ưu điểm

* Chạy tốt trên Windows 10/11 (không cần VBScript).
* Hỗ trợ Unicode đầy đủ.
* Giao diện tương tự `VBScript.RegExp`.
* Dùng được ngay trong Excel, Access, Word.

---

Nếu bạn đang bảo trì macro VBA cũ, hãy thay `VBScript.RegExp` bằng **ScriptHelper.RegExp** để code tiếp tục chạy ổn định trên Windows mới.



1758680439371.png

Giao diện sau khi đăng ký COM thành công nếu Add DLL sử dụng trong VBA sẽ thấy các hàm cơ bản như trên

vọc chơi cho vui lúc rảnh hai ngày tạm định hình xong thư viện cơ bản .... thong thả và dong chơi nếu thích bổ sung thêm các hàm tiện ích khác

đính kèm File phía dưới là COM DLL 64 bít vậy chỉ sử dụng cho Excel 64 bít ... nếu ai dùng bản 32 bít thì báo Tôi úp thêm
kèm các ví dụ sử dụng trong File Excel các kiểu


Password WinRaR là : 123
 

File đính kèm

Lần chỉnh sửa cuối:
# Hướng dẫn đăng ký & sử dụng ScriptHelper.RegExp trong VBA

## Đăng ký DLL

1. Copy file `ScriptHelper.dll` vào thư mục tùy ý (ví dụ `C:\Tools\ScriptHelper\`).
2. Mở CMD với quyền **Administrator** và chạy lệnh:
Mã:
   regsvr32 "C:\Tools\ScriptHelper\ScriptHelper.dll"

Nếu hiện thông báo `DllRegisterServer in ScriptHelper.dll succeeded` nghĩa là đã đăng ký thành công.

## ✅ Kiểm tra DLL trong VBA
1. Mở **VBA Editor** (Alt+F11 trong Excel/Word/Access).
2. Vào menu **Tools → References**.
3. Tìm và tick chọn **ScriptHelper RegExp**.

* Nếu thấy trong danh sách → DLL đã đăng ký thành công.
* Nếu không thấy → kiểm tra lại lệnh `regsvr32` và đường dẫn DLL.

Sau khi tick chọn, bạn có thể khai báo kiểu dữ liệu cụ thể:

Dim re As ScriptHelper.RegExp
→ sẽ có IntelliSense hỗ trợ (early binding).

## ‍ Demo đầy đủ (Early Binding)

Mã:
'---------------------------------------------
' Module: RegexExamples\_EarlyBinding
' Purpose: Demo all features of ScriptHelper.RegExp (early binding)
'---------------------------------------------
Option Explicit

Sub RunAllRegexExamples\_EarlyBinding()
Call Example\_4Digit
Call Example\_CatDog
Call Example\_Email
Call Example\_Decimal
Call Example\_UppercaseReplace
Call Example\_Date
Call Example\_URL
End Sub

'-----------------------------
' Example 1: Find 4-digit numbers
'-----------------------------
Sub Example\_4Digit()
Dim re As ScriptHelper.RegExp
Dim matches As Variant, m As Variant

```
Set re = New ScriptHelper.RegExp
re.Pattern = "\b\d{4}\b"
re.IgnoreCase = True
re.Global = True

matches = re.Execute("Year 2025, month 09, day 23")
Debug.Print "Example 1 - 4-digit numbers:"
For Each m In matches
    Debug.Print m
Next
```

End Sub

'-----------------------------
' Example 2: Find all "cat" or "dog"
'-----------------------------
Sub Example\_CatDog()
Dim re As ScriptHelper.RegExp
Dim matches As Variant, m As Variant

```
Set re = New ScriptHelper.RegExp
re.Pattern = "\b(cat|dog)\b"
re.IgnoreCase = True
re.Global = True

matches = re.Execute("I have a Cat, a dog, and a bird")
Debug.Print "Example 2 - Cat or Dog:"
For Each m In matches
    Debug.Print m
Next
```

End Sub

'-----------------------------
' Example 3: Find basic emails
'-----------------------------
Sub Example\_Email()
Dim re As ScriptHelper.RegExp
Dim matches As Variant, m As Variant

```
Set re = New ScriptHelper.RegExp
re.Pattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
re.IgnoreCase = True
re.Global = True

matches = re.Execute("Mail me at test@example.com or admin@site.org")
Debug.Print "Example 3 - Emails:"
For Each m In matches
    Debug.Print m
Next
```

End Sub

'-----------------------------
' Example 4: Find decimals
'-----------------------------
Sub Example\_Decimal()
Dim re As ScriptHelper.RegExp
Dim matches As Variant, m As Variant

```
Set re = New ScriptHelper.RegExp
re.Pattern = "\b\d+\.\d+\b"
re.IgnoreCase = True
re.Global = True

matches = re.Execute("Pi ~ 3.14, e ~ 2.718")
Debug.Print "Example 4 - Decimals:"
For Each m In matches
    Debug.Print m
Next
```

End Sub

'-----------------------------
' Example 5: Replace all uppercase letters with "X"
'-----------------------------
Sub Example\_UppercaseReplace()
Dim re As ScriptHelper.RegExp

```
Set re = New ScriptHelper.RegExp
re.Pattern = "[A-Z]"
re.IgnoreCase = False
re.Global = True

Debug.Print "Example 5 - Replace uppercase:"
Debug.Print re.Replace("AbCdeFG", "X")  ' Output: XbXdexXx
```

End Sub

'-----------------------------
' Example 6: Find dates dd/mm/yyyy
'-----------------------------
Sub Example\_Date()
Dim re As ScriptHelper.RegExp
Dim matches As Variant, m As Variant

```
Set re = New ScriptHelper.RegExp
re.Pattern = "\b\d{2}/\d{2}/\d{4}\b"
re.IgnoreCase = True
re.Global = True

matches = re.Execute("Today: 23/09/2025, Tomorrow: 24/09/2025")
Debug.Print "Example 6 - Dates:"
For Each m In matches
    Debug.Print m
Next
```

End Sub

'-----------------------------
' Example 7: Find basic URLs
'-----------------------------
Sub Example\_URL()
Dim re As ScriptHelper.RegExp
Dim matches As Variant, m As Variant

```
Set re = New ScriptHelper.RegExp
re.Pattern = "https?://[^\s]+"
re.IgnoreCase = True
re.Global = True

matches = re.Execute("Visit https://example.com and http://site.org/page")
Debug.Print "Example 7 - URLs:"
For Each m In matches
    Debug.Print m
Next
```

End Sub
 
Lần chỉnh sửa cuối:
Kieu Manh đổi sang PhuongNam mà cứ tưởng ai chứ :)
 
hai ngày à ơi chơi cho vui lúc rảnh tạo khung DLL xong rồi giờ thích gì thêm vào nhanh lắm 15 phút sau + ChatGPT có bộ siệu tập hàm bổ sung cho xử lý chuỗi mì tôm cua các kiểu thôi ... nó quá đơn giản với tôi khi có Em trợ lý ChatGPT + Copilot

Viết chuẩn COM DLL và có ghi chú tiếng Anh cho ai cần nếu không biết tiếng anh thì nhờ Google nó dịch cho
Ví dụ

Mã:
Function GetGroupValueByIndex(Text As String, Index As Long)
    Member of ScriptHelper.RegExp
    Returns the value of a captured group by its index from the first match in the input text.

Google nó sẽ dịch là
Mã:
Dòng tiếng Anh:

"Returns the value of a captured group by its index from the first match in the input text."

→ Dịch sang tiếng Việt chuẩn trong ngữ cảnh VBA như sau:

"Trả về giá trị của một nhóm được bắt theo chỉ số từ kết quả khớp đầu tiên trong chuỗi đầu vào."

1758764889582.png
 
vba hơi phức tạp, mình thích dùng .bat hơn !
 
éc, ngôn ngữ .bat là tên gọi phổ biến mà, cụ google thử sẽ thấy, mặc dù tên gọi chính thức là Batch, ít phổ biến hơn,
code thì chỉ cần Notepad là chạy được !
 

File đính kèm

  • Batch.jpg
    Batch.jpg
    31.8 KB · Đọc: 12
éc, ngôn ngữ .bat là tên gọi phổ biến mà, cụ google thử sẽ thấy, mặc dù tên gọi chính thức là Batch, ít phổ biến hơn,
code thì chỉ cần Notepad là chạy được !
thôi he tự nhiên lôi nó vào đây làm gì ... chủ đề này theo tiêu đề của nó mà ... nếu có vui vẽ chút không sao cả nhưng nó làm lạc đề rồi

tạo thớt mới ta bàn về .bat he
 
Làm gì có cái gì gọi là "ngôn ngữ .bat / Batch". Sợ luôn.
Google đấy. Bảo người ta tra ở Google mà mình đã làm chưa.

1758780486718.png
 
Lần chỉnh sửa cuối:
1758851610049.png

chiều qua và sáng nay rảnh à ơi cùng Em ChatGPT viết xong thư viện cho chủ đề này là Thuần C++ Builder

sơ bộ có trên 1000 dòng mã thôi ... khoãng trên 30 hàm C++ builder thuần

ai đó keo Tôi không có khả năng viết C++ được ... xem hình trước he ............ khi nào gió lên tạo Github sẽ úp DLL + chỉ dẫn

Giao diện thư viện C++ COM DLL từ VBA nhìn như sau ... chuẩn COM DLL + Help String

1758851942001.png
 
Bản mở rộng của chủ đề này với nhiều hàm tiện ích được viết thuần C++ Builder đã cho lên github.com

ai quan tâm có thể tải sử dụng Free vào bất cứ mục đích nào họ thích ??!!!

Đã bao gồm 32 và 64 bít COM DLL và các ví dụ mẫu sử dụng

1758934241625.png

Downloads
 
Lần chỉnh sửa cuối:
1758936828659.png
rất chi tiết và rõ ràng tôn trọng các kỹ sư lập trình tạo nên thư viện System.RegularExpressions cho Tôi viết hàm trung gian kế thừa từ nó
đó là thực tế phơi bày sự thật
 
kỳ này tôi đang rảnh dò mất một ngày lúc rảnh cuối cùng cũng Tìm ra Phương pháp viết Hàm duyệt For Each m In matches
Từ VBA .... rất chi là khó viết thành công trên C++ Builder mã sẽ có cấu trúc như sau _)(#;

Mã:
Sub FindWords()
    Dim re As Object, matches As Object, m As Object
    Set re = CreateObject("RegXHelper.RegExp")
  
    re.pattern = "(\w+)"
    re.ignoreCase = True
    re.Global = True
  
    Set matches = re.FindMatches("Hello world from VBA")
  
    Debug.Print "Cac tu tim duoc:"
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub

Hình ảnh xem qua sẽ như sau

Mã:
Function FindMatches(Text As String) As RegXMatchCollection
    Member of RegXHelper.RegExp
    Finds all matches of the regular expression in the input text and returns them as a collection.

1759196674499.png

Em ChatGPT Trợ lý Viết bài + Code mô tả như sau

## Giới thiệu hàm `FindMatches` trong thư viện RegXHelper

Hàm `FindMatches` là một phương thức tiện ích mạnh mẽ trong thư viện COM **RegXHelper.RegExp**, cho phép người dùng VBA dễ dàng tìm kiếm các chuỗi khớp với biểu thức chính quy trong một đoạn văn bản. Đây là công cụ lý tưởng để xử lý dữ liệu văn bản, kiểm tra định dạng, hoặc trích xuất thông tin như số điện thoại, email, mã số, v.v.

---

### ✅ Cách sử dụng trong VBA

```vb
Sub FindPhoneNumbers()
Dim re As Object
Set re = CreateObject("RegXHelper.RegExp")

re.Pattern = "(0\d{9}|\+84\d{9})"
re.IgnoreCase = True
re.Global = True

Dim matches As Object, m As Object
Set matches = re.FindMatches("Goi 0901234567 hoac +84901234567 de biet them.")

Debug.Print "So dien thoai tim duoc:"
For Each m In matches
Debug.Print m.Value
Next
End Sub
```

---

### Giải thích

- `Pattern`: biểu thức chính quy để tìm số điện thoại Việt Nam
- `IgnoreCase`: không phân biệt chữ hoa/thường
- `Global`: tìm tất cả các kết quả khớp
- `FindMatches(...)`: trả về một **collection** các đối tượng `IRegXMatch`
- `For Each m In matches`: duyệt từng kết quả khớp một cách đơn giản và trực quan

---

### Lợi ích khi dùng `FindMatches`

- **Dễ tích hợp** vào các macro VBA hiện có
- **Tương thích hoàn toàn với For Each** — không cần xử lý mảng phức tạp
- **Truy cập nhanh thông tin khớp** như `.Value`, `.Index`, `.Length`, và `.Groups`
- **Tốc độ cao** nhờ sử dụng thư viện RegEx gốc của Delphi

---
 
1759199915643.png

Rảnh viết nó thử chơi ... COM Wrapper ... còn chủ đề này cất kho
 
Lằng nhằng chỗ Pattern: nhiều ký hiệu, khó nhớ
nó là tiêu chuẩn chung rồi ... đang fix lại chút rảnh úp bản cập nhật lên Github các hàm mới như sau

dò xuất hàm duyệt theo tiêu chuẩn For Each m In matches khó vãi kinh mà lại viết trên C++ builder

vậy là mô phỏng theo thư viện của Ms thành công và thêm nhiều hàm tiện ích khác

đây là Class hổ trợ cho VBA duyệt For Each m In matches
Mã:
Class RegXMatchCollection
    Member of RegXHelper
    RegXMatchCollection Object


Hình ảnh bao gồm 3 Class
1759209807786.png

Class sau nữa cũng chỉ hổ trợ cho Class chính là RegExp

1759209888045.png

Tất cả gói gọn trong một DLL viết thuần C++ Builder

Mã:
' Module: RegXHelperExamples
' Mo ta: Cac vi du phuc tap su dung thu vien COM RegXHelper

Sub FindWords()
    Dim re As Object, matches As Object, m As Object
    Set re = CreateObject("RegXHelper.RegExp")
 
    re.pattern = "(\w+)"
    re.ignoreCase = True
    re.Global = True
 
    Set matches = re.FindMatches("Hello world from VBA")
 
    Debug.Print "Cac tu tim duoc:"
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub

Sub FindEmails()
    Dim re As Object, matches As Object, m As Object
    Set re = CreateObject("RegXHelper.RegExp")
 
    re.pattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}"
    re.ignoreCase = True
    re.Global = True
 
    Set matches = re.FindMatches("Lien he: kieu@example.com, test123@domain.vn")
 
    Debug.Print "Email tim duoc:"
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub

Sub FindPhoneNumbers()
    Dim re As Object, matches As Object, m As Object
    Set re = CreateObject("RegXHelper.RegExp")
 
    re.pattern = "(0\d{9}|\+84\d{9})" ' ? B? \b d? kh?p dúng
    re.ignoreCase = True
    re.Global = True
 
    Set matches = re.FindMatches("Goi 0901234567 hoac +84901234567 de biet them.")
 
    Debug.Print "So dien thoai tim duoc:"
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub


Sub FindCapitalizedWords()
    Dim re As Object, matches As Object, m As Object
    Set re = CreateObject("RegXHelper.RegExp")
 
    re.pattern = "\b[A-Z][a-z]+\b"
    re.ignoreCase = False
    re.Global = True
 
    Set matches = re.FindMatches("Hanoi is the Capital of Vietnam. Saigon is vibrant.")
 
    Debug.Print "Tu viet hoa:"
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub

Sub FindQuotedText()
    Dim re As Object, matches As Object, m As Object
    Set re = CreateObject("RegXHelper.RegExp")
 
    re.pattern = """(.*?)"""
    re.ignoreCase = True
    re.Global = True
 
    Set matches = re.FindMatches("He said: ""Hello world"" and then ""Goodbye""")
 
    Debug.Print "Doan trong dau ngoac kep:"
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub


Sub Test_FindMatches()
    Dim re As Object
    Set re = CreateObject("RegXHelper.RegExp")
 
    re.pattern = "(\w+)"
    re.ignoreCase = True
    re.Global = True
 
    Dim matches As Object
    Set matches = re.FindMatches("Hello world from VBA")
 
    Dim m As Object
    For Each m In matches
        Debug.Print m.Value
    Next
End Sub

1759210684966.png
 
Lần chỉnh sửa cuối:
đã cập nhật DLL là 32 và 64 bít viết thuần C++ Builder lên github như mô tả bài 19

Hãy nhìn vào Help String đọc kỹ trước khi sử dụng vì có nhiều hàm có chức năng như nhau nhưng khác nhau thuật toán nên Tôi lưu lại
thử nghiệm và học

có hai Hàm hổ trợ duyệt For Each m In matches là FindMatches ExecuteEx

Mã:
Function FindMatches(Text As String) As RegXMatchCollection
    Member of RegXHelper.RegExp
    Finds all matches of the regular expression in the input text and returns them as a collection.


Mã:
Function ExecuteEx(Text As String) As RegXMatchCollection
    Member of RegXHelper.RegExp
    Executes the regular expression on the input text and returns all matches as a collection.


Downloads
 
tìm ra phương pháp viết rồi rảnh chơi nhanh tay chút Buổi sáng xong thư Viện DictHelper trên C++ Builder mô phỏng như "Scripting.Dictionary" của VBA tạm xong Khung

quá đơn giản cũng là trò chơi cho vui và đi vào thực tiễn chứ không phải vài trò Demos "Hello Word" _)()(-_)(#;

1759454571934.png

Cách sử dụng mọi cái Y trang "Scripting.Dictionary" Của Ms

1759454670661.png

Code đơn giản như sau
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

Code phức tạp chút như sau

Mã:
Option Explicit

' Tao doi tuong Dictionary COM
Private Function CreateDict() As Object
    Set CreateDict = CreateObject("DictHelper.Dictionary")
End Function

' 1. Loc gia tri duy nhat
Public Sub FilterUnique()
    Dim dict As Object, name As Variant
    Dim names As Variant: names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan")

    Set dict = CreateDict()

    For Each name In names
        If Not dict.Exists(name) Then dict.Add name, True
    Next

    Debug.Print "Ten duy nhat:"
    Dim key As Variant
    For Each key In dict
        Debug.Print key
    Next
End Sub

' 2. Dem so lan xuat hien
Public Sub CountOccurrences()
    Dim dict As Object, name As Variant
    Dim names As Variant: names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan", "Lan")

    Set dict = CreateDict()

    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

    Debug.Print "Tan suat xuat hien:"
    Dim key As Variant
    For Each key In dict
        Debug.Print key & " xuat hien " & dict.GetItem(key) & " lan"
    Next
End Sub

' 3. Loc trung lap
Public Sub FilterDuplicates()
    Dim dict As Object, result As Object, name As Variant, key As Variant
    Dim names As Variant: names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan", "Lan", "Hoa", "Hoa")

    Set dict = CreateDict()
    Set result = CreateDict()

    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

    For Each key In dict
        If dict.GetItem(key) > 1 Then result.Add key, dict.GetItem(key)
    Next

    Debug.Print "Ten trung lap:"
    For Each key In result
        Debug.Print key & " xuat hien " & result.GetItem(key) & " lan"
    Next
End Sub

' 4. Sap xep theo tan suat giam dan
Public Sub SortByFrequency()
    Dim dict As Object, result As Object, name As Variant, key As Variant
    Dim names As Variant: names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan", "Lan", "Hoa", "Hoa")

    Set dict = CreateDict()
    Set result = CreateDict()

    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

    For Each key In dict
        If dict.GetItem(key) > 1 Then result.Add key, dict.GetItem(key)
    Next

    Dim sortedKeys() As Variant, i As Long, j As Long, temp As Variant
    ReDim sortedKeys(result.Count - 1)
    i = 0
    For Each key In result
        sortedKeys(i) = key
        i = i + 1
    Next

    For i = LBound(sortedKeys) To UBound(sortedKeys) - 1
        For j = i + 1 To UBound(sortedKeys)
            If result.GetItem(sortedKeys(j)) > result.GetItem(sortedKeys(i)) Then
                temp = sortedKeys(i)
                sortedKeys(i) = sortedKeys(j)
                sortedKeys(j) = temp
            End If
        Next j
    Next i

    Debug.Print "Ten trung lap (sap xep giam dan):"
    For i = LBound(sortedKeys) To UBound(sortedKeys)
        key = sortedKeys(i)
        Debug.Print key & " xuat hien " & result.GetItem(key) & " lan"
    Next
End Sub

' 5. Loc theo dieu kien ket hop
Public Sub FilterByLengthAndFrequency()
    Dim dict As Object, name As Variant, key As Variant
    Dim names As Variant: names = Array("Kieu", "Lan", "Hoa", "Kieu", "Minh", "Lan", "Tuan", "Hoa", "Hoa")

    Set dict = CreateDict()

    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

    Debug.Print "Ten dai hon 3 ky tu va xuat hien > 1 lan:"
    For Each key In dict
        If Len(key) > 3 And dict.GetItem(key) > 1 Then
            Debug.Print key & " xuat hien " & dict.GetItem(key) & " lan"
        End If
    Next
End Sub

Cách sử dụng khác

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

quá đơn giản chỉ vài khai báo xong cái Dic mô phỏng như của Ms ... Chơi vào hôm xong cho lên Github
 
Lần chỉnh sửa cuối:

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

Back
Top Bottom