Home > OS >  How to read in an excel file to MS Access database and run data validations against it using VBA?
How to read in an excel file to MS Access database and run data validations against it using VBA?

Time:09-24

I've been reading about many methods that could potentially do this but nothing seems definitive or completely applicative to my situation.

What I want to do is read in an excel file from my desktop (within MS Access VBA) and then while reading it in I want to run a series of data validations against it. Such as check if the cell at B16 is a certain value or if it is a certain string. I need to be able to loop through rows while checking values and summing values. Think of an excel file with a lot of accounting terms and numbers. How would I go about validating that data?

I am currently able to read in excel files and add them to access db tables using:

DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "MyTbl", _
            Me.txtFileName, True, "Sheet1!"

I've also read about using recordsets, using ActiveX Data Objects, and using DoCmd.TransferDatabase acLink.

Import data from Excel into MS Access

Best way to read an Excel file into an Access database

CodePudding user response:

You say "and then while reading it in". That's not possible to do while DoCmd.TransferSpreadsheet is executing.

But you can loop through all rows using Recordset after you have read it in (MyTbl is assumed to be name of table). COL1, COL2, COL3 are example field names, but use the ones in your Sheet1. If Sheet1 does not have column header names, then your field names will be of the form Field1, Field2, etc:

    Dim rs As Recordset
    
    Set rs = CurrentDb.OpenRecordset("MyTbl")
    While Not rs.EOF
        ' you can perform your validations here by referencing values of your fields.
        Debug.Print rs.Fields("COL1"), rs.Fields("COL2"), rs.Fields("COL3")
        ' next row
        rs.MoveNext
    Wend
    Set rs = Nothing
  • Related