【问题标题】:navigating through table records in Access VBA在 Access VBA 中浏览表记录
【发布时间】:2012-06-25 15:28:00
【问题描述】:

我有一个包含两列(value1 和 value2)的表,这些值从最低到最高排序。示例:

Value1
20
40
43
90
100
122

Value2
4
5
9
10
15
18

我要求用户输入一个输入值,然后我计算 CalcFinalValue 的值,该值可以通过以下方式之一计算:

  1. 如果用户输入的值已经存在于value1字段中,则返回字段value2中对应的值。例如,如果用户输入为 100,则 CalcFinalValue 将为 15

  2. 如果value1字段中不存在用户输入的值,则在value1字段中定位输入值之间的两个值(例如如果输入值为42,我想定位40和43 来自 value1 字段)。计算 CalcFinalValue 为: CalcFinalValue=(40*9)+(43*5)/42

换句话说,公式将是: CalcFinalValue=(中间值的LowerValue *中间值的HigherValue的查找值)+(中间值的HigherValue *中间值的LowerValue的查找值)/(用户输入值) 我想在 Access 2007 VBA 中执行此操作。

我希望这很清楚。提前感谢您的帮助!

【问题讨论】:

    标签: ms-access vba


    【解决方案1】:
    Dim rs AS DAO.Recordset
    Set rs = CurrentDb.OpenRecordset("TableName", dbOpenTable)
    
    ' inp stores the user input value; i counts the number of records that have been accessed
    Dim inp, i as Integer
    ' r2c1 and r2c2 store the data of the second row in case the two-row calculation is needed 
    Dim r2c1, r2c2 as integer
    
    ' Since I mostly use forms for I/O that's what I've used here
    '   Change this to whatever method you use to get the user input
    inp = Forms!FormName.InputTextBoxName.Value
    i = 0
    rs.MoveFirst
    Do While (Not rs.EOF)
        i = i + 1
        ' Check if the user input exists in the table
        If (rs.Fields("Value1") = inp) Then
            ' Again use whatever output method you want
            Set Forms!FormName.OutputTextBoxName.Value = rs.Fields("Value1")
            End Do
        ' Otherwise, check if the current value in column 1 is greater than the input
        Else If (rs.Fields("Value1") > inp) Then
            ' If this is true for the first row then the input is less than the lowest number.
            ' I assume this is out-of-bounds, but use whatever boundary condition you want
            If (i = 1) Then
                MsgBox("Out of Bounds", vbOkOnly)
            Else 
                ' Save the required values from this row
                r2c2 = rs.Fields("Value2")
                r2c1 = rs.Fields("Value1")
                ' Goto previous row which and calculate according to your formula
                rs.MoveLast
                Set Forms!FormName.OutputTextBoxName.Value = (r2c1*r2c2 + rs.Fields("Value1")*rs.Fields("Value2"))/inp
            End If 
        End If 
        rs.MoveNext
    Loop
    ' If nothing was found, the input was larger than all values in 'Value1'
    If (rs.EOF) Then
        MsgBox("Out of Bounds", vbOkOnly)
    End If
    

    将 Value1 和 Value2 替换为您使用的任何列名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多