UDF - 确定它是重新计算还是首次执行

时间:2017-09-14 14:03:12

标签: excel excel-vba vba

我想编写一个UDF来查询访问数据库。我想知道是否可以有2个不同的工作流程,这取决于它是第一次执行还是仅重新计算UDF。
理想情况下,我会有一个UDF,您可以提供db的主键,UDF提供了访问db表的可能值的概述。如果是重新计算,我不想再次使用userform弹出窗口。这有可能吗?有人能指出我正确的方向吗? 谢谢!

修改 尝试显示一些(虚拟)代码:

public function key_from_table(primarykey as string) as string
' Read-out column names from Access table for userform
' Trigger userform with possible column names and let user choose
' readout Chosen column names
key_from_table = Call get_from_db(Primary_key, column_names)
end function

Function get_from_db(Primarykey as string, column_names as string) as string
'call Access db and readout result
end Function 

如果触发重新计算,则会再次出现userform弹出窗口 我还是Excel vba的新手 - 请告诉我这是不是很愚蠢:)

2 个答案:

答案 0 :(得分:1)

声明一个全局字典变量。在触发表单之前,检查字典是否已经具有列名称。如果是,请不要触发表单。如果没有,则触发表单并在关闭表单后将列名添加到字典中。您可以清除Workbook_BeforeClose中的变量,只是为了清洁

答案 1 :(得分:0)

这样的事情对你有用:

Public pub_sRecalcCheck As String

Public Function MyTest() As Boolean

    Dim bReCalc As Boolean

    If InStr(1, " " & pub_sRecalcCheck & " ", " " & Application.Caller.Address(External:=True) & " ", vbTextCompare) = 0 Then
        'This is a brand new calculation
        'Add this cell to the public variable storing where calculations for this UDF have occurred
        bReCalc = False
        pub_sRecalcCheck = WorksheetFunction.Trim(Replace(pub_sRecalcCheck, " " & rCell.Address(External:=True) & " ", " "))

        ''''''''''''''''''''''''''''''''''''''''''''
        '                                          '
        '    Your code here for new calculation    '
        '                                          '
        ''''''''''''''''''''''''''''''''''''''''''''

    Else
        'This is a recalculation
        bReCalc = True

        ''''''''''''''''''''''''''''''''''''''''''
        '                                        '
        '    Your code here for recalcuations    '
        '                                        '
        ''''''''''''''''''''''''''''''''''''''''''

    End If

    MyTest = bReCalc

End Function

编辑:如果公式从单元格中删除,请在ThisWorkbook模块中使用它来从RecalcCheck公共字符串变量中清除该单元格的地址,这样如果将新公式放在那里,则将其视为新计算:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

    Dim rCell As Range

    For Each rCell In Target.Cells
        'Check if cell has been deleted/cleared
        If IsEmpty(rCell) Then
            'Found deleted cell, check if it is stored for the recalc checks
            If InStr(1, " " & pub_sRecalcCheck & " ", " " & rCell.Address(External:=True) & " ", vbTextCompare) > 0 Then
                'It is stored, remove it so that if formula is put back it is treated as a new calculation
                pub_sRecalcCheck = WorksheetFunction.Trim(Replace(pub_sRecalcCheck, " " & rCell.Address(External:=True) & " ", " "))
            End If
        End If

    Next rCell

End Sub