473,625 Members | 3,329 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

VBA Code to ensure data just sent to Access from Excel are not duplicates

7 New Member
Hi folks - I am in need of help please
I am trying to de-duplicate data coming from Excel to Access
The part I am having problems with is
(I have attached the full code at the bottom too to help)
Any help would be greatly appreciated and needed


Expand|Select|Wrap|Line Numbers
  1. Set DBz = _
  2.     OpenDatabase("C:\Documents and Settings\_XXXXX_\My Documents\S_B\7-16-A_D_B.mdb")
  3. Set rsz = DBz.OpenRecordset("Data_Weekly", dbOpenTable)
  4.  
  5.  
  6. With ThisWorkbook.Worksheets("Data_Weekly")
  7.      ExcelRecord = Advocatecomp & MDate
  8. End With
  9.  
  10. AccessRecord = rsz.Fields("Value") & rsz.Fields("Date")
  11.  
  12. If ExcelRecord = AccessRecord Then
  13.    bFound = True
  14.    Call MsgBox("Advocate Work Completed on time Metrics already exist in the ADB" _
  15.                & vbCrLf & "Please click ok to cancel this import" _
  16.                , vbCritical, "LLF- Ca")
  17.  
  18.                Exit Sub
  19.  
  20. Else
  21.   bFound = False
  22.      Call MsgBox("Advocate Work Completed on time Metrics Do Not Already exist in the ADB" _
  23.                & vbCrLf & "Please click ok to import this metric" _
  24.                , vbCritical, "LLF- Ca")
  25. End If


Expand|Select|Wrap|Line Numbers
  1. Public Sub SaveWPPercent()
  2. Dim MDate As Date
  3. Dim Rptpath As String
  4. Dim RptName As String
  5. Dim DateCheck As Date
  6. Dim Advocatecomp As Single
  7. Dim X As Single
  8.  
  9. Dim MSQL As String
  10. Dim DBS As DAO.Database
  11. Dim RST As DAO.Recordset
  12. Dim DBSName As String
  13. Dim dBSPath As String
  14. Dim Mmetric_ID As Single
  15. '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  16. Dim bFound As Boolean 'new 7-15
  17. Dim ExcelRecord As String 'new 7-15
  18. Dim AccessRecord As String 'new 7-15
  19. Dim DBz As Database, rsz As DAO.Recordset, r As Long 'new  7-15
  20. '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  21. 'open the report
  22. 'check to make sure the date matches
  23. 'find the metric ID in the ADB
  24. 'save the value to the weekly data table
  25. 'if the value is already there, then replace it
  26.  
  27. 'make sure there is a date in the date box----------------------------------------------------------------------------------------
  28. If Not IsDate(Me.cboWE.Value) Then
  29.     MsgBox "Please select a week ending date!", vbCritical, "Error"
  30.     Exit Sub
  31. Else
  32.     MDate = Me.cboWE.Value
  33. End If
  34.  
  35. 'make sure report there is a report chosen----------------------------------------------------------------------------------------
  36. If Me.txtWorkPackage = "" Then
  37.     MsgBox "Please enter a valid report path for Advocate Completed on Time!", vbCritical, "Error"
  38.     Exit Sub
  39. Else
  40.     Rptpath = Me.txtWorkPackage
  41. End If
  42.  
  43. 'check to see if the dates match--------------------------------------------------------------------------------------------------
  44. Workbooks.Open Rptpath, False, True
  45. RptName = ActiveWorkbook.Name
  46. DateCheck = Workbooks(RptName).Worksheets("Input Sheet").Cells(2, 1)
  47. If DateCheck <> MDate Then
  48.     If MsgBox("The date in the workbook: " & RptName & " do not match! Do you wish to continue?", vbYesNo, "Error! Dates do not match!") = vbYes Then
  49.         MsgBox "The value will be assigned to the weekending date of " & MDate & "!"
  50.     Else
  51.         Exit Sub
  52.     End If
  53.  
  54. End If
  55.  
  56. 'find the Advocate completed on time metric for Italy--------------------------------------------------------------------------------
  57. For X = 1 To 25
  58.     If Workbooks(RptName).Worksheets("Input Sheet").Cells(X, 3).Value = "Italy total (calc=1)" Then
  59.         'we have found the row
  60.         Advocatecomp = Workbooks(RptName).Worksheets("Input Sheet").Cells(X, 5).Value
  61.         Workbooks(RptName).Close False
  62.         Exit For
  63.     End If
  64.  
  65. Next X
  66.  
  67. 'If there is no data then --------------------------------------------------------------------------------------------------------
  68. If Advocatecomp = 0 Then
  69.     MsgBox "Unable to locate the Italy Advocate completed on time value!", vbCritical, "Error!"
  70.     Exit Sub
  71. End If
  72.  
  73. 'SQL to set data -----------------------------------------------------------------------------------------------------------------
  74.  MSQL = " SELECT Metrics.Metric, Reporting_Hierarchy.Level_1, Metrics_X_Reporting_Hierarchy.Metric_ID, Data_Weekly.Date, " _
  75.  & "Data_Weekly.Value " _
  76.  & "FROM ((Metrics_X_Reporting_Hierarchy INNER JOIN Metrics ON Metrics_X_Reporting_Hierarchy.Metric_Name_ID = Metrics.Metric_Name_ID) " _
  77.  & "INNER JOIN Reporting_Hierarchy ON Metrics_X_Reporting_Hierarchy.Hierarchy_ID = Reporting_Hierarchy.Hierarchy_ID) " _
  78.  & "INNER JOIN Data_Weekly ON Metrics_X_Reporting_Hierarchy.Metric_ID = Data_weekly.Metric_ID " _
  79.  & "WHERE (((Metrics.Metric)='" & "Advocate Completed On Time - Weekly" & "') " _
  80.  & "AND ((Reporting_Hierarchy.Level_1)='" & "Italy" & "') " _
  81.  & "AND ((Data_weekly.Date)='" & MDate & "'));"
  82.  
  83. 'set the variable-----------------------------------------------------------------------------------------------------------------
  84. bFound = False 'added 7-16
  85.  
  86. 'where is the path and name of the access file -----------------------------------------------------------------------------------
  87. dBSPath = "C:\Documents and Settings\ra94\My Documents\Scorecard_Button"
  88. DBSName = "7-16-MOS_Data_Repository.mdb"
  89.  
  90. 'set DBS--------------------------------------------------------------------------------------------------------------------------
  91. Set DBS = OpenDatabase(dBSPath & "\" & DBSName)
  92.  
  93. 'set record set-------------------------------------------------------------------------------------------------------------------
  94. Set RST = DBS.OpenRecordset(MSQL)
  95. If Not RST.EOF Then
  96.     'record exists, find the record in the data_montly table and edit the value of the existing record
  97.     'add to restatement and notify the user
  98.  
  99.         Mmetric_ID = RST!metric_ID
  100.         Set RST = Nothing 'want to reuse the variable - need to clear it out.
  101.         MSQL = "SELECT Data_weekly.Metric_ID, Data_weekly.Date, Data_weekly.Value " _
  102.         & "FROM Data_weekly " _
  103.         & "WHERE (((Data_weekly.Metric_ID)= " & Mmetric_ID & ") " _
  104.         & "AND ((Data_weekly.Date)='" & MDate & "'));"
  105.         Set RST = DBS.OpenRecordset(MSQL)
  106.         RST.MoveFirst
  107.         RST.Edit
  108.         RST!Value = Advocatecomp
  109. '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  110. Set DBz = _
  111.     OpenDatabase("C:\Documents and Settings\_XXXXX_\My Documents\S_B\7-16-A_D_B.mdb")
  112. Set rsz = DBz.OpenRecordset("Data_Weekly", dbOpenTable)
  113.  
  114.  
  115. With ThisWorkbook.Worksheets("Data_Weekly")
  116.      ExcelRecord = Advocatecomp & MDate
  117. End With
  118.  
  119. AccessRecord = rsz.Fields("Value") & rsz.Fields("Date")
  120.  
  121. If ExcelRecord = AccessRecord Then
  122.    bFound = True
  123.    Call MsgBox("Advocate Work Completed on time Metrics already exist in the ADB" _
  124.                & vbCrLf & "Please click ok to cancel this import" _
  125.                , vbCritical, "LLF- Ca")
  126.  
  127.                Exit Sub
  128.  
  129. Else
  130.   bFound = False
  131.      Call MsgBox("Advocate Work Completed on time Metrics Do Not Already exist in the ADB" _
  132.                & vbCrLf & "Please click ok to import this metric" _
  133.                , vbCritical, "LLF- Ca")
  134. End If
  135. '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  136.         RST.Update
  137.         Set RST = Nothing
  138.  
  139.  
  140. Else
  141.     'record doesn't exist.  Find the metric_ID in the CR table - if the metric id is found, insert the record into the data_monthly table
  142.  
  143.      MSQL = "SELECT Reporting_Hierarchy.Level_1, Metrics.Metric, Metrics_X_Reporting_Hierarchy.Metric_ID " _
  144.      & "FROM (Reporting_Hierarchy INNER JOIN Metrics_X_Reporting_Hierarchy ON Reporting_Hierarchy.Hierarchy_ID = Metrics_X_Reporting_Hierarchy.Hierarchy_ID) " _
  145.      & "INNER JOIN Metrics ON Metrics_X_Reporting_Hierarchy.Metric_Name_ID = Metrics.Metric_Name_ID " _
  146.      & "WHERE (((Reporting_Hierarchy.Level_1)= '" & "Italy" & "') " _
  147.      & "AND ((Metrics.Metric)= '" & "Advocate Completed On Time - Weekly" & "'));"
  148.  
  149.  
  150.       Set RST = DBS.OpenRecordset(MSQL)
  151.       RST.MoveFirst
  152.       Mmetric_ID = RST!metric_ID
  153.       Set RST = Nothing
  154.       MSQL = "Select * from Data_Weekly"
  155.       Set RST = DBS.OpenRecordset(MSQL)
  156.       RST.AddNew
  157.       RST!Date = MDate
  158.       RST!metric_ID = Mmetric_ID
  159.       RST!Value = Advocatecomp
  160.       RST!Status = "Active"
  161.       RST.Update
  162.       Set RST = Nothing
  163.     MsgBox "Metrics have been imported!", vbOKOnly, "Import Completed!" 'moved from import click to here
  164. End If
  165.  
  166.  
  167. End Sub
  168.  
Jul 16 '10 #1
13 4737
nico5038
3,080 Recognized Expert Specialist
Just curious why the user has to click for ignoring duplicates.

I would have excluded them entirely from the data set to be inspected, or ignored them and issued an INSERT that will skip dupes for the specified unique key field(s).

What's the way you intend this code to work?

Nic;o)
Jul 17 '10 #2
mxtreme
7 New Member
Hi Nico thanks for getting to my thread I could really use your help. All I need is to make sure the data being imported via a command button if pressed more then once that the data does not duplicate as many as extra times the button was pressed. So lets say you press that button to import metrics into access. But another co-worker did not check access to see if the data is there, and they press the button to import the data again. I need to block this from happening. Please advise
Jul 17 '10 #3
nico5038
3,080 Recognized Expert Specialist
As indicated, when inserting a new record, Access will "block" duplicates when you have defined the unique ID.

I see your add code:
RST!Date = MDate
RST!metric_ID = Mmetric_ID
RST!Value = Advocatecomp
RST!Status = "Active"
and I assume MDate, Mmetric_ID and Advocatecomp make up the unique record. Thus defining a unique index on the table consisting from these fields with the option "No duplicates allowed" will make sure no duplicate records can be added.

I normally issue a "Docmd.exec ute ("<Insert statement>")" to add rows and this will suppress error messages when adding a duplicate row, as it won't add the data.

Still would need some information on the "Status" field. When there's a row with Status <> "Active", will this trigger the Status field to change ?

Nic;o)
Jul 17 '10 #4
mxtreme
7 New Member
Nico again thank you so much. You are a bit over my head - could you simplify things or please give the code to exit sub if found?
Jul 17 '10 #5
nico5038
3,080 Recognized Expert Specialist
The whole point is that I don't check for duplicates, I just add all rows and Access will "drop" the duplicates because of the defined unique key in the table.

Normally I import an excel sheet into a temp table and show that to the user in a form. Here I add an indication showing duplicates yes or no. (using an outer (left or right) join with the production table.)
Thus the user can see which rows will be added and check for typo's causing erroneous duplicates. After correcting this the final import can be executed "straight away" with an "append" query, no code needed.

What is the reason to show the rows first to the user, instead of importing it directly?

Nic;o)
Jul 17 '10 #6
mxtreme
7 New Member
Nico - I think I am getting it now.
Can you show me a code where this will take my data and do your method with a form? I know I am asking a lot but I would really appreciate it
Jul 17 '10 #7
nico5038
3,080 Recognized Expert Specialist
Just attach (part of) the .mdb and a sample excelsheet to your post (Use "Go Advanced" button) so I can show you.
(I'm lazy, I know :-)

Nic;o)
Jul 17 '10 #8
mxtreme
7 New Member
great will do when I get the file after the weekend.
May I ask why is this not working?


Expand|Select|Wrap|Line Numbers
  1. Private Sub CommandButton1_Click()
  2. On Error GoTo errline
  3.  
  4.  
  5. ' exports data from the active worksheet to a table in an Access database
  6. ' this procedure must be edited before use
  7. Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
  8.     ' connect to the Access database
  9.     Set cn = New ADODB.Connection
  10.     cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
  11.         "Data Source=C:\Documents and Settings\Ben\My Documents\Excel VBA\7-18.mdb;"
  12.     ' open a recordset
  13.     Set rs = New ADODB.Recordset
  14.     rs.Open "Table1", cn, adOpenKeyset, adLockOptimistic, adCmdTable
  15.     ' all records in a table
  16.     r = 2 ' the start row in the worksheet
  17.     Do While Len(Range("A" & r).Formula) > 0
  18.     ' repeat until first empty cell in column A
  19.         With rs
  20.             .AddNew ' create a new record
  21.             ' add values to each field in the record
  22.             .Fields("date") = Range("A" & r).Value
  23.             .Fields("item") = Range("B" & r).Value
  24.             .Fields("number") = Range("C" & r).Value
  25.             ' add more fields if necessary...
  26.             .Update ' stores the new record
  27.  
  28.  
  29.         End With
  30.         r = r + 1 ' next row
  31.     Loop
  32. exitline:
  33. Exit Sub
  34.  
  35. errline:
  36.  Select Case Error.Number
  37.  Case 2147217887
  38.  MsgBox "This would cause duplicates in the MDR click OK to cancel"
  39.  Cancel = True
  40.  
  41.  Case Else
  42.  MsgBox "There was an error in the program please contact MOS Administrator"
  43.   GoTo exitline
  44.   End Select
  45.     rs.Close
  46.     Set rs = Nothing
  47.     cn.Close
  48.     Set cn = Nothing
  49.  
  50.  
  51. End Sub
Jul 17 '10 #9
nico5038
3,080 Recognized Expert Specialist
Hmm, the Range looks a bit odd, as it's an excel method and I would have expected automation instead of recordset processing. Once a sheet has been opened as a recordset, the origin (text, excel, access, etc.) doesn't bother.

In general I just use linked excel sheets to get all handling similar.

Nic;o)
Jul 18 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

12
2289
by: Marc Ederis | last post by:
Hello, I'm having a problem with sending data with sockets over a dial-up connection. When I use the send function, it will happily send a buffer of a megabyte and more in one shot. But of course, the data is still in the network buffer... Meaning you can't disconnect for awhile (but for how long...). The problem is, how can I know when it's done? Is there a way to be notified when the data has truly been sent? I tried using...
3
9237
by: sridevi | last post by:
Hello How to export data from ms-access database to excel worksheet using ASP. mainly i need to export data to multiple worksheets. it is very urgent to us. i have a sample code which works only exporting to single worksheet. but i need to export data to multiple worksheets. it is very urgent to us. so please help me in code.
4
14768
by: Paolo | last post by:
Friends, I need help with some code to export different tables to a single spreadsheet in Excel. My excel file is named REPORT and the spreadsheet is named CLIENTS. I do have the code to export a single table to Excel but have problems with multimple tables. Thanks.
2
6115
by: PrinStation | last post by:
I am looking to import data from Excel to Access. The data is set up in one Excel file, but on 12 (monthly) sheets. After importing the first month/sheet (which I did successfully), I was looking to use the old dBase 3 plus command "append" to bring in the eleven remaining sheets. I am thus far unable to find "append" or rather its Access equivalant. What to do? Any help is appreciated.
4
13461
by: Martin | last post by:
There is an Access table on the network. 15 users who do not have Access are connected to the network. Is there a way for each user to be able to enter one or more rows containing 3 or 4 columns to Excel on his machine and then press a button or something and append that data to the Access table on the network? Any suggestions on what the code would be? Thank you very much! Martin
8
2002
by: Steve Jorgensen | last post by:
Hi folks, I'm posting this message because it's an issue I come up against relatively often, but I can't find any writings on the subject, and I haven't been able to figure out even what key words one would use to look for it. First, in broad philosophical terms, code actually -is- data. Code is the data that's fed into a compiler, interpreter, or microprocessor that tells it what to do. Code execution is, then, just a form another...
1
11635
by: tkaleb | last post by:
I have to create output file in a text, MS Access, MS Excel and .dbf format from C# Win/ADO.NET application. Data are collected in DataSet and there is no problem to make text file. However, I have to create a new output files (tables with defined fields) in other 3 formats, and to fill them with data from DataSet. I created Excel output with ComponentOne's trial Excel component, but it is a temporary solution. Also I have unusual CP (1250...
13
13219
by: nuti | last post by:
Hi all, I am fairly new to VB.I am trying to figure out as how to write a script so that i can read the data from an excel sheet to Access. can u guys please help me out? cheers, nuti
3
7142
by: =?Utf-8?B?YzY3NjIyOA==?= | last post by:
Hi all, I have a question for you. I have a .csv file which has many lines of data. Each line has many data fields which are delimited by ",". Now I need to extract part of data from this file but save it as an excel file. The data in this excel file will be imported into an Access database. The
1
1413
by: dkriese | last post by:
I am using Quickbooks reporting tool that can export an xls or csv file. The data being exported needs to create a classroom scheduler. The data being exported is from a sales receipt via QB and contains date and time, etc. Question is how can I get that row of data imported into access to create a calendar type schedule for those days and for the month. I need to see all the students scheduled for the each of the dates, the class...
0
8256
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8356
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7184
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4193
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1500
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.