vba - 将包含多个值的访问字段分隔到具有正确对应数据的唯一行
问题描述
我在 Access 中有一个字段,其中有多个逗号分隔值(字段一的值"1, 2, 3, 4"
在第二行1, "2, 2, 3"
的行中)。
第一个字段中有1-7
(但可以大到1,101
)值。
第二个字段将具有与 Field1 的行对应的相同数量的值,
然而,逗号的位置可能很奇怪(我假设这可以在分析此字段时使用修剪或左偏移函数来解决“,” 1, 2, 3
)。
我需要的是让成千上万的这些行不再有重复的条目,并且它们每一个都是自己的行。可扩展的解决方案很重要,并且允许使用整个 Microsoft Office 套件。
从一行:
Field1 Field2
1, 2, 3, 4 , 1, 1, 4, 4
2, 2, 3 , 2, 3, 3
输出如下所示:
Field1 Field2
1 1
2 1
3 4
4 4
2 2
2 3
3 3
解决方案
这是你想要的:
Sub GetNumbers()
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select Field1, Field2 From Table1")
Do While Not rs.EOF
'Get the fields values and 'trim away' any blanks.
Dim field1 As String
field1 = Trim(rs("Field1").Value)
Dim field2 As String
field2 = Trim(rs("Field2").Value)
'If the strings now begin with a ',', remove it.
If Left(field1, 1) = "," Then field1 = Mid(field1, 2)
If Left(field2, 1) = "," Then field2 = Mid(field2, 2)
'Split the strings to an array by ','
Dim arrField1() As String
arrField1 = Split(field1, ",")
Dim arrField2() As String
arrField2 = Split(field2, ",")
'Loop the arrays (important is that the number of elements is equal in both arrays. This depends on your data!)
Dim index As Long
For index = LBound(arrField1) To UBound(arrField1)
'Output the values and again 'trim away' any blanks
Debug.Print Trim(arrField1(index)), Trim(arrField2(index))
'Here you also can store the values to another table if you want/need.
'If the new field is a text field:
'DoCmd.RunSQL "Insert Into Table2 (Field1, Field2) Values ('" & Trim(arrField1(index)) & "', '" & Trim(arrField2(index)) & "')"
'If the new field is a number field:
'DoCmd.RunSQL "Insert Into Table2 (Field1, Field2) Values (" & Trim(arrField1(index)) & ", " & Trim(arrField2(index)) & ")"
Next index
rs.MoveNext
Loop
End Sub
推荐阅读
- html - 如何使用显示拆分元素:使用 DomPDF 的两页表格
- php - Arranging data from sql database with php
- matlab - MATLAB custom colormap, accessible by name of color map as string (just as default color maps are)
- generics - Kotlin:invoke() 和参数化类的问题
- python - Inputting a number and returning the product of all the even integers between 1 and that number
- excel - 仅使用公式拆分分隔列
- prooph - 如何避免使用 prooph 的事件溯源?
- android - 如何避免由于自定义静态处理程序类导致的内存泄漏?
- c++ - SDL_RenderCopy 未渲染(不是 NULL,也没有 SDL/IMG 错误)
- ddev - ddev 开始卡在 Pulling web (drud/ddev-webserver:v1.4.0)