【问题标题】:Ms Access VBA: Return the Formula behind a Query FieldMs Access VBA:返回查询字段后面的公式
【发布时间】:2017-10-31 05:28:25
【问题描述】:

我有一个子过程,它将基于具有 2 个文本字段(FieldName 和 SourceName)的现有查询创建一个表。 FieldName 的值将是现有查询中每个字段的名称,SourceName 的值将是该字段来自的表或查询的名称。请参阅下面的代码。我要做的是将计算字段的公式也包含在名为 FieldFormula 的第三个字段中。有谁知道这是否可能?谢谢!

Option Compare Database

Public Sub MapQuery()

 Dim strQueryName As String
 Dim rst As DAO.Recordset
 Dim fld As Field
 Dim strSource As String
 Dim strField As String
 Dim strValue As String
 Dim strSQL1 As String
 Dim strSQL2 As String
 Dim booExists As Boolean


strQueryName = InputBox("Please enter the name of the query that you are looking to map")

   Set rst = CurrentDb.OpenRecordset(strQueryName)
    intLen = Len(strQueryName)
    strnewtablename = Right(strQueryName, intLen - 4)
On Error GoTo error1
    booExists = IsObject(CurrentDb.TableDefs(strnewtablename & " Definitions"))
    DoCmd.DeleteObject acTable, strnewtablename & " Definitions"
continue:
    strSQL1 = "CREATE TABLE [" & strnewtablename & " Definitions]" & " (FieldName CHAR, SourceName CHAR);"
    DoCmd.RunSQL (strSQL1)
    DoCmd.SetWarnings False
    For Each fld In rst.Fields

    strField = fld.Name
    strSource = fld.SourceTable


Debug.Print strValue

    strSQL2 = "INSERT INTO [" & strnewtablename & " Definitions]" & "(FieldName, SourceName) VALUES(""" & strField & """, """ & strSource & """);"

    DoCmd.RunSQL (strSQL2)
    Next fld

error1:
    If Err.Number = 3265 Then
        Resume continue
    Else
    MsgBox Err.Description

    End If

    DoCmd.SetWarnings True
    Exit Sub

    DoCmd.SetWarnings True
End Sub

【问题讨论】:

  • 有趣的问题。我不会查看Recordset.Fields,而是查看QueryDef.Fields.Item(x)。但粗略地看一眼“监视”窗口并没有显示出来。也许这些公式只存在于QueryDef.SQL 属性中,并被解析以显示在查询设计器网格中。
  • 如果它在任何地方,您应该可以从 fld.properties("expression") 中获取它,但它不会为我返回任何内容。见here

标签: ms-access vba


【解决方案1】:

从表计算字段中提取表达式很简单。我在 VBA 即时窗口中做了一个快速测试:

CurrentDb.TableDefs("Teams").Fields("Test").Properties("Expression")

然后返回表达式字符串。我希望您的代码必须执行条件语句来检查该字段是否为计算类型。

但是,如果要在查询中拉取计算字段的表达式,那就大不一样了。没有“表达式”属性,因为确实没有字段实体。我想说@Andre 用“仅存在于 QueryDef.SQL 属性中”作为语句字符串的一部分来解释它。

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    相关资源
    最近更新 更多