Access查询:将含无序变量的字符串拆分至指定有序列
解决MS Access中无序键值对字段拆分问题
步骤1:提取所有唯一键(确定目标列)
先通过VBA遍历数据,提取Field1里所有的键名(比如Type、Length这类),去重后得到需要新增的列名,再在数据表中添加对应文本型列。
VBA代码(按Alt+F11打开编辑器,插入模块后粘贴,替换你的表名):
Sub ExtractAllKeys() Dim db As DAO.Database Dim rs As DAO.Recordset Dim keyDict As Object Dim fieldParts As Variant Dim keyValue As Variant Dim key As String Set db = CurrentDb Set rs = db.OpenRecordset("YourTableName") '替换成你的表名 Set keyDict = CreateObject("Scripting.Dictionary") Do While Not rs.EOF If Not IsNull(rs!Field1) Then fieldParts = Split(rs!Field1, ";") For Each keyValue In fieldParts key = Split(keyValue, "=")(0) If Not keyDict.Exists(key) Then keyDict.Add key, 1 End If Next keyValue End If rs.MoveNext Loop '在立即窗口(Ctrl+G)查看所有键,复制后去表中新增列 For Each key In keyDict.Keys Debug.Print key Next key rs.Close Set rs = Nothing Set db = Nothing Set keyDict = Nothing End Sub
步骤2:创建提取值的自定义函数
在同一VBA模块中添加函数,用于根据键名从Field1中提取对应值:
Function GetKeyValue(sourceStr As String, targetKey As String) As String Dim fieldParts As Variant Dim keyValue As Variant Dim key As String Dim value As String If IsNull(sourceStr) Then GetKeyValue = "" Exit Function End If fieldParts = Split(sourceStr, ";") For Each keyValue In fieldParts keyValue = Trim(keyValue) If InStr(keyValue, "=") > 0 Then key = Split(keyValue, "=")(0) value = Mid(keyValue, InStr(keyValue, "=") + 1) If UCase(key) = UCase(targetKey) Then GetKeyValue = value Exit Function End If End If Next keyValue GetKeyValue = "" End Function
步骤3:用查询拆分数据
创建选择查询,添加你的表后,在字段行按如下格式填写:
Product:直接选择表中Product字段Type:GetKeyValue([Field1], "Type")Side:GetKeyValue([Field1], "Side")- 其他列同理替换对应的键名
运行查询即可得到目标格式的结果;若要直接更新到表中,可改为更新查询,将各目标列的值设为对应函数调用结果。
性能优化提示
针对10万+数据量:
- 给
Field1字段建立索引,加快遍历速度 - 运行更新查询时关闭其他程序,减少卡顿
- 若VBA执行较慢,可临时导出数据到Excel用Power Query处理后再导回Access
内容的提问来源于stack exchange,提问作者Matt Johnson
相关产品推荐
相关产品推荐

