【问题标题】:How to count number of fields in a table?如何计算表中的字段数?
【发布时间】:2013-10-18 15:06:16
【问题描述】:

我正在尝试在 Access 2010 中计算表中的字段数。我需要 vb 脚本吗?

【问题讨论】:

    标签: ms-access vba field ms-access-2010


    【解决方案1】:

    您可以从TableDefFields 集合的.Count 属性中检索表中的字段数。这是一个立即窗口示例(Ctrl+g 将带您到那里)...

    ? CurrentDb.TableDefs("tblFoo").Fields.Count
     13
    

    如果您实际上是指行数而不是字段数,则可以使用 TableDef RecordCount 属性或 DCount

    ? CurrentDb.TableDefs("tblFoo").RecordCount
     11 
    ? DCount("*", "tblFoo")
     11 
    

    【讨论】:

    • @HansUp,该死的我错过了那个。我总是忘记在即时窗口中工作
    • @Linger 你的回答让我怀疑这个问题是关于字段数还是行数,所以我都提供了。
    • 好吧,我觉得我很笨……我在 Access 的哪里运行这个命令?
    • 您可以使用 Ctrl+g 打开即时窗口并在那里执行这些语句。但是,如果您愿意,可以在 VBA 代码中使用这些相同的技术。
    【解决方案2】:

    使用查询:

    'To get the record count
    SELECT Count(*) FROM MyTable
    

    在 DAO 中它看起来像:

    Dim rst As DAO.Recordset
    Set rst = CurrentDb.OpenRecordset("SELECT * FROM MyTable")
    rst.MoveLast
    
    'To get the record count
    MsgBox ("You have " & rst.RecordCount & " records in this table")
    
    'To get the field count
    MsgBox ("You have " & rst.Fields.Count & " fields in this table")
    

    注意,在获取RecordCount 之前执行MoveLast 很重要。

    在 ADO 中它看起来像:

    Set conn = Server.CreateObject("ADODB.Connection")
    conn.Provider = "Microsoft.Jet.OLEDB.4.0"
    conn.Open(Server.Mappath("MyDatabaseName.mdb"))
    
    Set rst = Server.CreateObject("ADODB.recordset")
    rst.Open "SELECT * FROM MyTable", conn
    
    'To get the record count
    If rst.Supports(adApproxPosition) = True Then _
      MsgBox ("You have " & rst.RecordCount & " records in this table")
    
    'To get the field count
    MsgBox ("You have " & rst.Fields.Count & " fields in this table")
    

    【讨论】:

      【解决方案3】:

      快速简便的方法:将表格导出到 Excel 并突出显示第 1 行以获取列数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 1970-01-01
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多