Write Records to Existing Database Based on Criteria

mrmmickle1

Well-known Member
Joined
May 11, 2012
Messages
2,461
So I have an existing Database that has information in it that looks like this. The Chart Number is Unique and will not be repeated:

Excel 2012
ABCDEFGHIJ
1MRChart NumberClinic LocationLast NameFirst NameDate ReceivedSales RepresentativeHold ReasonDays PendingNotes
2G036373OF14-118606ABC ClinicDoeJohn8/5/20144544523
3G036342OF14-118610ABC ClinicLowseyBill8/5/20144545423Notes Here
4G036344OF14-118611DEF ClinicStoneMatt8/5/20148802123
Other

I have an Excel Spreadsheet that looks like this:


Excel 2012
ABCDEFGHI
1MRChart NumberClinic LocationLast NameFirst NameDate ReceivedSales RepresentativeHold ReasonDays Pending
2G036373OF14-118606ABC ClinicDoeJohn8/5/20144544523
3G036342OF14-118610ABC ClinicLowseyBill8/5/20144545423
4G036344OF14-118611DEF ClinicStoneMatt8/5/20148802123
Other


I would like to import records into my database from the Excel Spreadsheet. The Catch is that many of the records in the spreadsheet will have the same Chart Number as a record already in the database.

I would like to go through the data in my spreadsheet one row at a time starting in row 2 and compare the Chart Number in the spreadsheet to all Chart Numbers in the database. If the chart number does not exist I would like to write the record (Plain and Simple). However, if the Chart Number is already present in the database I would only like for Field "Pending_Days" to be updated. This way the user will be able to see any existing notes that are present in the database.

The current report that I process in Excel is processed every morning based off of a database export but it has no way of keeping notes in it because it is done every morning it would wipe out the information from the previous day. By keeping the notes related to the corresponding Chart Number it would save my staff an extreme amount of research and time. This is currently how I am writing records into the Database. Is there a simple way to add the If / Else logic into this Procedure. I have very little experience with MS Access VBA and would be greatly appreciative if someone could help me get this problem ironed out! :

Code:
 rs.Open "AllSamples", cn, adOpenKeyset, adLockOptimistic, adCmdTable
[COLOR=#008000]        ' all records in a table[/COLOR]
        r = 2 [COLOR=#008000]' the start row in the worksheet[/COLOR]
        [COLOR=#0000ff]Do While[/COLOR] Len(Range("A" & r).Formula) > 0
[COLOR=#008000]        ' repeat until first empty cell in column A[/COLOR]
            


            [COLOR=#0000ff]With [/COLOR]rs
                .AddNew [COLOR=#008000]' create a new record[/COLOR]


[COLOR=#008000]                ' add values to each field in the record[/COLOR]
                .Fields("MR_Num") = Range("A" & r).Value
                .Fields("Chart_Number") = Range("B" & r).Value
                .Fields("Clinic_Location") = Range("C" & r).Value 
                .Fields("Last_Name") = Range("D" & r).Value
                .Fields("First_Name") = Range("E" & r).Value
                .Fields("Date_Received") = Range("F" & r).Value
                .Fields("Sales_Rep") = Range("G" & r).Value
                .Fields("Hold_Reason") = Range("H" & r).Value
                .Fields("Pending_Days") = Range("I" & r).Value
[COLOR=#008000]                'There is an additional field entitled "Notes" in the database[/COLOR]
[COLOR=#008000]                'This field is not in the spreadsheet[/COLOR]


[COLOR=#008000]                ' add more fields if necessary...[/COLOR]
                .Update ' stores the new record
[COLOR=#0000ff]            End With[/COLOR]
            r = r + 1 [COLOR=#008000]' next row[/COLOR]
[COLOR=#0000ff]        Loop[/COLOR]
 

Excel Facts

How can you automate Excel?
Press Alt+F11 from Windows Excel to open the Visual Basic for Applications (VBA) editor.
By chance are you maintaining the Access Database?

If so you could link the Excel file to Access (External Data -> Excel assuming 2010-2013 Access), then afterwards it should be a simple append query to your existing Table where those chart number that does not exist. You could do an update query to set the "Pending_Days" field to whatever is in the linked excel file where those chart number do exist.

You do not really need VBA code for this.
 
Last edited:
Upvote 0
I may have oversimplified my data set. There are multiple tables in the database and multiple Sheets (10+) in the Workbook.

Currently the workbook I have is used like this:

1. Employee Exports Data From Corporate DataBase into CSV file.
2. Employee Delimits CSV Export
3. Employee copies data and pastes it on a specific sheet in my workbook
4. Each row from the database export is distributed to different sheets based on a lot of different criteria/rules
5. Now that the process is complete the employee saves the workbook and distributes it to 30 or 40 people

I have been able to patch together some code that will make a fresh database from the information contained in the daily workbook. However, I would like to keep the notes from one day to the next sense some of these Chart Numbers will stay on the Log for 10 - 20 days. Which is why I am in my current dilemma.

If I were to put both the spreadsheet and the Ms Access Database in a shared location so multiple users could access it would it possible for me to:

1. Link the Workbook to the Database?
2. Link each specific sheet to a specific table in the database?

If this is possible.....

1. How could I set up these worksheet to table links?
2. How would I make an Append Query that updates the data from the spreadsheet which is run every morning?
3. I only want Chart Numbers that are in the Daily Workbook to Exist in the Database. If a Chart Number Existed in the MS Access Database that did not occur in the Workbook it needs to be deleted from the Database.

The reason I am pushing the database is because a shared workbook is not feasible. We already have many problematic bloated shared workbooks that lock up and crash a lot (Once a week) so I am pushing the move into Access.
 
Last edited:
Upvote 0
Are the worksheets formatted the same? What makes the row unique in #4 above where it then gets pasted into the various sheets?

You can pretty much do all those items that you asked but you may not need to depending upon the answers to the above since the structure of both your Excel file and Access DB can come into play.
 
Last edited:
Upvote 0
The Log I am putting into Access is like a problem list. Once the problems are resolved they are removed from the list (Database Export). The issue is that some of these can stay on the "Problem List" for 10 -20 Days. These Chart Numbers would need to have notes added to them to specify what the hold up is. The issue is that the list is not 10 or 30 Chart Numbers it is Several Thousand (Usually Between 3000-4000). So the workbook I run now catches all of the problems and classifies them to certain problem types (Different Worksheets). The problem is that it's fresh everyday so no notes can be kept.

Here is an example. Say this was the information in Yesterday's Database:

Excel 2012
ABCDEFGHIJ
1MRChart NumberClinic LocationLast NameFirst NameDate ReceivedSales RepresentativeHold ReasonDays PendingNotes
2G036373OF14-118606ABC ClinicDoeJohn8/5/20144544523Wrong Test Run. Doing Test Again
3G036342OF14-118610ABC ClinicLowseyBill8/5/20144545423
4G036344OF14-118611DEF ClinicStoneMatt8/5/20148802123
521279OF14-127792EFG ClinicNarlyJill9/30/2014G10513
61193OF14-127793EFG ClinicKnowvilleMatt9/30/2014G10513Waiting on Clinic for Subject Info.

<tbody>
</tbody>
Other



And this is the information from the Fresh Excel Workbook in the morning:
Excel 2012
ABCDEFGHI
1MRChart NumberClinic LocationLast NameFirst NameDate ReceivedSales RepresentativeHold ReasonDays Pending
2G036373OF14-118606ABC ClinicDoeJohn8/5/20144544524
321279OF14-127792EFG ClinicNarlyJill9/30/2014G10514
41193OF14-127793EFG ClinicKnowvilleMatt9/30/2014G10514
555345OF14-127800RPG ClinicSwankyTyler10/1/2014345551
653214OF14-127801RPG ClinicHamerEileen10/2/2014343551

<tbody>
</tbody>
Other



When the Database is Updated then it will now look like this:

Excel 2012
ABCDEFGHIJ
1MRChart NumberClinic LocationLast NameFirst NameDate ReceivedSales RepresentativeHold ReasonDays PendingNotes
2G036373OF14-118606ABC ClinicDoeJohn8/5/20144544524Wrong Test Run. Doing Test Again
321279OF14-127792EFG ClinicNarlyJill9/30/2014G10514
41193OF14-127793EFG ClinicKnowvilleMatt9/30/2014G10514Waiting on Clinic for Subject Info.
555345OF14-127800RPG ClinicSwankyTyler10/1/2014345551
653214OF14-127801RPG ClinicHamerEileen10/2/2014343551

<tbody>
</tbody>
Other



The two Chart Numbers that are no longer in the spreadsheet are deleted from the database.

Excel 2012
ABCDEFGHIJ
3G036342OF14-118610ABC ClinicLowseyBill8/5/20144545423
4G036344OF14-118611DEF ClinicStoneMatt8/5/20148802123

<tbody>
</tbody>
Other



The two Chart Numbers that are not currently in the database are added to the database:
Excel 2012
ABCDEFGHI
555345OF14-127800RPG ClinicSwankyTyler10/1/2014345551
653214OF14-127801RPG ClinicHamerEileen10/2/2014343551

<tbody>
</tbody>
Other




And the Days Pending are updated in the records that were already in the database:
Excel 2012
ABCDEFGHIJ
2G036373OF14-118606ABC ClinicDoeJohn8/5/20144544524Wrong Test Run. Doing Test Again
321279OF14-127792EFG ClinicNarlyJill9/30/2014G10514
41193OF14-127793EFG ClinicKnowvilleMatt9/30/2014G10514Waiting on Clinic for Subject Info.

<tbody>
</tbody>
Other
 
Last edited:
Upvote 0
Would it be possible for you to create another column in the raw data set after it has been updated (I'm assuming it gets extracted as 1 worksheet), with the problem type? Name the column 'Problem Type' then you must have some logic that identifies these records as something right?(like a formula etc or macro in Excel)

Having all the records in 1 table is a lot easier as well as using queries to identify what problem type you want could be pulled to Excel easier -(you could do a drop down with the problem types etc and Excel can pull that from Access if that is what your end product is).

By doing it this way we could also date stamp the import if it will be a daily process as you described to further help with all the updates that you will need. You could even keep instances of the imports of the data since it's date stamped.

Presumably everything will ultimately be in 1 master table that you will need afterwards.
 
Upvote 0
TerryHogarth21,

I'll work on getting this data into a single table. As you mentioned, I feel like once the data is in one table it will be easier to work with. Once I have the data in one table I will reply back with a new example. It may take a few days.

Thanks for your reply.
 
Upvote 0
TerryHogarth21,

I was able to get the data into a single table. As of right now I am using some code that I pieced together to export the current day's table from access:

Code:
[COLOR=#0000ff]Public Sub [/COLOR]ExportPendingSamplesTable()


   [COLOR=#0000ff] Dim[/COLOR] ws               [COLOR=#0000ff] As[/COLOR] Worksheet
   [COLOR=#0000ff] Dim[/COLOR] strTable         [COLOR=#0000ff] As String[/COLOR]
 [COLOR=#0000ff]   Dim[/COLOR] CurrentAccessDB   [COLOR=#0000ff]As String[/COLOR]
 [COLOR=#0000ff]   Dim[/COLOR] adoRecSet        [COLOR=#0000ff] As Object[/COLOR][COLOR=#008000] 'As New ADODB.Recordset[/COLOR]
[COLOR=#0000ff]    Dim[/COLOR] connDB            [COLOR=#0000ff]As Object [/COLOR][COLOR=#008000]'As New ADODB.Connection[/COLOR]
 [COLOR=#0000ff]   Dim[/COLOR] rng              [COLOR=#0000ff] As[/COLOR] Range
 [COLOR=#0000ff]   Dim[/COLOR] i                [COLOR=#0000ff] As Long[/COLOR]
   [COLOR=#0000ff] Dim[/COLOR] lFieldCount       [COLOR=#0000ff]As Long[/COLOR]


    ChDrive ("M")
    ChDir ("M:\Science\Toxicology\MS Access Pending Log")
    CurrentAccessDB = Application.GetOpenFilename(FileFilter:="Access Files ( .ACCDB), *.MDB", Title:="Select Pending Log Database")
   [COLOR=#0000ff] Set[/COLOR] connDB = CreateObject("ADODB.Connection")
    connDB.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data source=" & CurrentAccessDB


   [COLOR=#0000ff] Set [/COLOR]ws = ActiveWorkbook.Sheets("AccessImport")
[COLOR=#0000ff]    Set[/COLOR] rng = ws.Range("A1")
   [COLOR=#0000ff] Set [/COLOR]adoRecSet = CreateObject("ADODB.Recordset")  
    strTable = "PendingSamples"


    adoRecSet.Open Source:=strTable, ActiveConnection:=connDB, CursorType:=adOpenKeyset, LockType:=adLockOptimistic
    lFieldCount = adoRecSet.Fields.count
     
  [COLOR=#0000ff]  For[/COLOR] i = 0 [COLOR=#0000ff]To[/COLOR] lFieldCount - 1
        rng.Offset(0, i).Value = adoRecSet.Fields(i).name
    [COLOR=#0000ff]Next[/COLOR] i   
    
    rng.Offset(1, 0).CopyFromRecordset adoRecSet
    adoRecSet.Close
    
[COLOR=#008000]    'Clear Memory[/COLOR]
   [COLOR=#0000ff] Set [/COLOR]ws = [COLOR=#0000ff]Nothing[/COLOR]
 [COLOR=#0000ff]   Set[/COLOR] rng = [COLOR=#0000ff]Nothing[/COLOR]
  [COLOR=#0000ff]  Set [/COLOR]adoRecSet = [COLOR=#0000ff]Nothing[/COLOR]
 [COLOR=#0000ff]   Set[/COLOR] connDB = [COLOR=#0000ff]Nothing[/COLOR]
    strTable = vbNullstring
    CurrentAccessDB = vbNullstring
    i =[COLOR=#0000ff] Empty[/COLOR]
    lFieldCount = [COLOR=#0000ff]Empty[/COLOR]
[COLOR=#0000ff]  [/COLOR]
[COLOR=#0000ff]End Sub[/COLOR]

Once I have the Table back into Excel I just run a Vlookup on the New Data's Unique ID to get any notes that need to be carried over, copy this column as values and then create a new table with the updated notes.

I would be interested in another method. What I have works but I feel it is an inferior method.
My table looks like this now:

Excel 2012
ABCDEFGHIJK
1TypeMRChart NumberClinic LocationLast NameFirst NameDate ReceivedSales RepresentativeHold ReasonDays PendingNotes
2GenG036373HG14-118606ABC ClinicDoeJohn418564544524Wrong Test Run. Doing Test Again
3Gen21279HG14-127792EFG ClinicNarlyJill41912G1051Slow Processing4
4Gen1193HG14-127793EFG ClinicKnowvilleMatt41912G10514Waiting on Clinic for Subject Info.
Sheet1
 
Upvote 0

Forum statistics

Threads
1,215,544
Messages
6,125,434
Members
449,223
Latest member
Narrian

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top