比较表格,创建列并指定值

时间:2018-06-18 17:50:46

标签: access-vba

我无法弄清楚如何在Access VBA中执行此操作。我能够在Excel vba中使用它,但由于大小限制,有必要切换到Access。

所以,这是交易。我有1个主表,还有多个其他表,我将比较主表。我需要做的是检查主表中的每条记录是否存在于每个辅助表中,创建一个带有辅助表名的字段,如果记录存在则分配1,如果没有匹配则分配0。

示例:

MAIN_TABLE

ID ---说明

1 --- A

2 ---乙

3 ---ç

4 --- d

5 ---ë

secondary_table_name

ID ---说明

2 ---乙

3 ---ç

运行宏

MAIN_TABLE

ID --- ---说明secondary_table_name

1 --- A --- 0

2 --- ---乙1

3 --- --- c ^ 1

4 --- --- d 0

5 --- ---ë0

我知道这可能有很多要问,但任何亮点都会有很多帮助。

编辑: 所以我集思广益,提出了一个不错的解决方案,所以我会把它扔出去,万一有人需要这样的东西。 代码:

Sub a()

Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim guia1 As String
Dim SQL As String
Dim arquivoTeste As String
Dim strInput As String
Dim strMsg As String
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Set db = CurrentDb

strMsg = "Favor informar o novo do arquivo referente ao razão geral"
strInput = InputBox(Prompt:=strMsg, title:="INICIO")

StartTime = Timer


For Each tdf In db.TableDefs
    ' ignore system and temporary tables
    If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like strInput) Then
        SQL = "ALTER TABLE [razaoGeral] ADD COLUMN [" & tdf.Name & "] INTEGER"

        DoCmd.RunSQL SQL

        Set rs1 = CurrentDb.OpenRecordset(strInput)

        Set rs2 = CurrentDb.OpenRecordset(tdf.Name)

        rs1.MoveFirst
        rs2.MoveFirst

        Do Until rs2.EOF
            guia2 = Trim(Str(rs2("Coluna guia")))
            rs1.MoveFirst
            Do Until rs1.EOF
                guia1 = Trim(Str(rs1("Coluna_guia")))
                If guia1 = guia2 Then
                    rs1.Edit
                    rs1(tdf.Name) = 1
                    rs1.Update
                End If

                rs1.MoveNext

            Loop

            rs2.MoveNext

        Loop

    End If

    Set rs1 = Nothing
    Set rs2 = Nothing

Next

Set tdf = Nothing

Set db = Nothing

SecondsElapsed = Round(Timer - StartTime, 2)

MsgBox "Macro finalizada em " & SecondsElapsed & " segundos", vbInformation

End Sub

0 个答案:

没有答案