Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS Access copy table to another table VBA code

I have a problem I need to create vba code for ms access 2016 which will copy the contents of table 1 to table 2 with

If there are duplicates in Table 2, it displays a message about the duplicates and a question whether to continue or abort.

I have this vba code but I don't know how to convert it to work the way I want I got this error on image

My error

Private Sub txtVWI_BeforeUpdate(Cancel As Integer)
On Error GoTo Err_txtVWI_BeforeUpdate
Dim intResponse As Integer
Dim strTable As String
Dim strFind As String
Dim strSQL As String
Dim rst As ADODB.Recordset
Dim Conn As ADODB.Connection
Set Conn = CurrentProject.Connection
Set rst = New ADODB.Recordset
strTable = "Główna"
strSQL = "SELECT Count(Główna.Data/Godzina) AS Duplikaty" & _ " FROM Główna" & _ " GROUP BY Główna.Data/Godzina" & _ " HAVING Count(Główna.Data/Godzina)>1"
Set rs = db.OpenRecordset(strSQL) 
If rs.RecordCount = 0 Then strSQL = "INSERT INTO Główna" & _     " SELECT Tymczasowa.*" & _     " FROM Tymczasowa"     DoCmd.RunSQL (strSQL)
rst.Open strSQL, Conn
If rst(0) > 0 Then ' duplikaty znalezione.
    If Me.NewRecord Then
        intResponse = MsgBox("Ten zestaw danych już istnieje" & vbCrLf & "chcesz zduplikować zestaw danych?", vbYesNo)
            If intResponse = vbNo Then
                Me.Undo
            End If
    End If
End If
Exit_txtVWI_BeforeUpdate:
    Exit Sub

        rst.Close
        Conn.Close
        Set rst = Nothing
        Set Conn = Nothing
Err_txtVWI_BeforeUpdate:
    MsgBox Err.Description
    Resume Exit_txtVWI_BeforeUpdate
End Sub
like image 774
Wojtek Avatar asked Jan 27 '26 16:01

Wojtek


1 Answers

If you are going to use concatenation and line continuation character then should actually continue on next line.

Table name has special character. Use [] to delimit. Can simplify SQL statement.

Not seeing db variable declared and set. Don't really need it for one-time use. Should declare rs variable.

Dim rs As DAO.Recordset
strSQL = "SELECT Count(*) AS Duplikaty" & _ 
          " FROM Główna" & _ 
          " GROUP BY [Data/Godzina]" & _ 
          " HAVING Count(*)>1"
Set rs = CurrentDb.OpenRecordset(strSQL) 
If rs.RecordCount = 0 Then strSQL = "INSERT INTO Główna" & _
         " SELECT Tymczasowa.*" & _
         " FROM Tymczasowa"

Advise not to use punctuation/special characters in naming convention.

like image 91
June7 Avatar answered Jan 30 '26 18:01

June7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!