简体   繁体   English

如何将 excel 文件读入 MS Access 数据库并使用 VBA 对其运行数据验证?

[英]How to read in an excel file to MS Access database and run data validations against it using VBA?

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.我想要做的是从我的桌面(在 MS Access VBA 中)读取 excel 文件,然后在读取它时我想对其运行一系列数据验证。 Such as check if the cell at B16 is a certain value or if it is a certain string.比如检查B16处的单元格是某个值还是某个字符串。 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.想想一个包含大量会计条款和数字的 excel 文件。 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:我目前能够读取 excel 文件并将它们添加到使用以下方法访问数据库表:

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.我还阅读了有关使用记录集、使用 ActiveX 数据对象和使用 DoCmd.TransferDatabase acLink 的信息。

Import data from Excel into MS Access 将数据从 Excel 导入 MS Access

Best way to read an Excel file into an Access database 将 Excel 文件读入 Access 数据库的最佳方法

You say "and then while reading it in".您说“然后在阅读时”。 That's not possible to do while DoCmd.TransferSpreadsheet is executing.在执行 DoCmd.TransferSpreadsheet 时这是不可能的。

But you can loop through all rows using Recordset after you have read it in (MyTnl is assumed to be name of table).但是您可以在读入 Recordset 后使用 Recordset 遍历所有行(假定 MyTnl 是表的名称)。 COL1, COL2, COL3 are example field names, but use the ones in your Sheet1. COL1、COL2、COL3 是示例字段名称,但请使用 Sheet1 中的名称。 If Sheet1 does not have column header names, then your field names will be of the form Field1, Field2, etc:如果 Sheet1 没有列 header 名称,那么您的字段名称将采用 Field1、Field2 等形式:

    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM