2023.3.26双字典双字典结构如图访_Vba
2023.3.26 双字典
双字典结构如图 访问 key 8001 的 Item 又包含字典2 ,这是数组做不到的
新建模块
Public 单字典 As Object, 双字典 As Object
ThisWorkBook 中
Private Sub Workbook_Open()
Set 双字典 = CreateObject("Scripting.Dictionary")
End Sub
Sheet中 创建双字典
Private Sub Btn批量添加_Click()
Dim Range账号 As String
Dim RowsCount As Integer, Column_Count As Integer, iCol As Integer
For Each SR In Selection.Rows
'SR 是 selection Row 缩写 , 属于自定义变量
'账号 作为双字典主 key
' 筛所不符合记录 RowHeight = 0 ,而相符记录 RowHeight >0 才添加到双字典中
If Cells(SR.Row, iCol).RowHeight > 0 Then
Range账号 = Cells(SR.Row, iCol)
If Range账号 <> "" Then
'嵌套第二个字典
If Not 双字典.Exists(Range账号) Then
Set 双字典(Range账号) = CreateObject("Scripting.Dictionary")
For i = 1 To Column_Count
'标题作嵌套字典的 Key
ikey = Cells(4, i)
双字典(Range账号)(ikey) = Cells(SR.Row, i)
Next
End If
End If
End If
Next
End Sub
重点 - 通过函数调用
调用原理
dKeys =双字典.keys
dKeys(iKs) 通过 iKs 返回对应 key 值
双字典(dKey(iKs)) 返回的是内容
代码缩减如下:
‘调用格式, iKs 从0开始
Sub btnPrint()
For i = 1 To 双字典.Count
SetDict 双字典.keys, i - 1
next
End Sub
Sub SetDict(dKeys, iKs)
If 双字典(dKeys(iKs)).Exists(“户名”) Then Msgbox "Exists"
End Sub
原代码有点复杂,包括正则表达式 , 有兴趣看下
注:Sub_字典 代表子过程字典
Sub Set_Dict(dKeys, iKs)
'dkeys 双字典keys ,iK 传递循环次数 获取key值 比如: dKeys(iK) -> 双字典(dKeys(iK)("户名")
Sub_字典.RemoveAll
For iRow = 1 To 50
For iCol = 1 To 50
regEx.Pattern = "【([\u4e00-\u9fa5\w①-⑨]+)(:|:)*(<*[\u4e00-\u9fa5\w,,]*>*)】"
'【意见:同意】 【经办:<法人>】 【财务】 效果如下:
' M(0) = 【意见:同意】 M(0).SubMatches(0) = 意见 ,M(0).SubMatches(1) = :,M(0).SubMatches(2) = 同意
' M(0) = 【经办:<法人>】 M(0).SubMatches(0) = 经办 ,M(0).SubMatches(1) = :,M(0).SubMatches(2) = <法人>
' M(0) = 【财务】 M(0).SubMatches(0) = 财务 ,M(0).SubMatches(1) = ,M(0).SubMatches(2) =
sText = Sheets(ComboBox1.Text).Cells(iRow, iCol)
If regEx.test(sText) Then
'如果匹配到
Set M = regEx.Execute(sText)
'将执行结果赋给 对像 M
If M(0).SubMatches(2) = "" Then
'就算结果只有一条 , 也要在 M 后面加上 (0)
'如果【财务】包含在 双字典
If 双字典(dKeys(iKs)).Exists(M(0).SubMatches(0)) Then
Sub_字典(M(0).SubMatches(0)) = 双字典(dKeys(iKs))(M(0).SubMatches(0))
Else
Sub_字典(M(0).SubMatches(0)) = ""
'匹配 【财务】
'Sub_字典 的 Key 为 M(0).SubMatches(0) = 财务
'后面没有参数 ,相当于 Sub_字典(财务) = ""
End If
Else
regEx.Pattern = "[<>]+"
'重点:第一个正则表达式执行结果存放在 对像 M 中 ,
'这里重新修改正则表达式的规则 < >
'所以要将第一个正则写在循环内,不停交替
If regEx.test(M(0).SubMatches(2)) Then
'匹配 【经办:<法人>】
' 其中 <法人> 对应 双字典 中的 Key
Sub_字典(M(0).SubMatches(0)) = 双字典(dKeys(iKs))(regEx.Replace(M(0).SubMatches(2), ""))
'< > 用Replace 替换"" , 变成 字典_1( 法人 )
'相当于 Sub_字典(经办) = "李X"
Else
Sub_字典(M(0).SubMatches(0)) = M(0).SubMatches(2)
'匹配 【意见:同意】 , 相当于 Sub_字典(意见) = "同意"
End If
End If
End If
Next
Next
End Sub
Excel Vba 表格打印分享