单独的访问字段,其中包含具有适当对应数据的唯一行的多个值

问题描述 投票:-1回答:2

我在Access中有一个字段,其中有多个逗号分隔值(字段1在第二行的行"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
vba ms-access access
2个回答
0
投票

这是如何进行的广泛概述。您将不得不自己完成详细的工作,因为这个网站是为了解决您没有为您编写代码的问题。

  • 循环记录。每个: 使用Replace将“,”替换为“,” 使用像IIF(Left([Field2],1=",",Right([Field2],Len([Field2])-1),[Filed2])这样的东西清理引导逗号。同样,如果有必要,可以使用尾随逗号 使用Split将两个字段分解为字符串数组。 使用UBound确定每条记录中的数字(两个字段应该相同,因此无论您测试哪一个都无关紧要)。 使用For循环遍历数组 使用像DoCmd.RunSQL "INSERT INTO MyCleanedUpTable (Field1, Field2) VALUES (" & Field1Array(i) & "," & Field2Array(i) & ")"这样的东西将每对添加到新的清理表中。

0
投票

这是你想要的:

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
© www.soinside.com 2019 - 2024. All rights reserved.