How to Insert a Variable Number of Records into an Access Table Based on a Fields Value

后端 未结 2 1109
猫巷女王i
猫巷女王i 2021-01-26 08:33

I have an Access Table with the following columns: WeeklyID(PrimaryKey), CampaignID(Foreignkey), WeekEnded(Date Field), Duration(Number Field).

I want to automatically a

2条回答
  •  长发绾君心
    2021-01-26 09:07

    You can modify this function to have lngCount as a fixed value:

    Public Sub CopyEmptyRecords()
    
      Dim rstSource   As DAO.Recordset
      Dim rstInsert   As DAO.Recordset
      Dim fld         As DAO.Field
      Dim strSQL      As String
      Dim lngLoop     As Long
      Dim lngCount    As Long
      Dim booCopy     As Boolean
    
      strSQL = "SELECT * FROM tblStats"
      Set rstSource = CurrentDb.OpenRecordset(strSQL)
    
      strSQL = "SELECT TOP 1 * FROM tblStatsNull"
      Set rstInsert = CurrentDb.OpenRecordset(strSQL)
    
      With rstSource
        .MoveLast
        .MoveFirst
        lngCount = .RecordCount            ' Set to fixed value of 7.
        For lngLoop = 1 To lngCount
          With rstInsert
            booCopy = False
            .AddNew
              For Each fld In rstSource.Fields
                With fld
                  If .Attributes And dbAutoIncrField Then
                    ' Skip Autonumber or GUID field.
                  Else
                    ' Copy field content.
                    rstInsert.Fields(.Name).Value = .Value
                    If Len(Trim(Nz(.Value, vbNullString))) = 0 Then
                      booCopy = True
                    End If
                  End If
                End With
              Next
            If booCopy = True Then
              .Update
            Else
              .CancelUpdate
            End If
          End With
          .MoveNext
        Next
        rstInsert.Close
        .Close
      End With
    
      Set rstInsert = Nothing
      Set rstSource = Nothing
    
    End Sub
    

提交回复
热议问题