简体   繁体   English

如何在MS Access VBA中创建共享功能?

[英]How can I create a shared function in ms access VBA?

I have a form that runs some sql on the form load and three sort buttons on the form that all repeat the sql in their own private function. 我有一个在窗体加载时运行一些sql的窗体,以及在窗体上的三个排序按钮,它们均在其自己的私有函数中重复该sql。 The only difference is the sort order. 唯一的区别是排序顺序。 When I need to update the where clause, I have to update it 4 times. 当我需要更新where子句时,我必须对其进行4次更新。 I would like to created a parameterized function like 我想创建一个像

function getFormRecs(arg){
    sql...
    . 
    .
    .
    order by 'arg'
{

where arg is the argument passed in from the form control or event. 其中arg是从表单控件或事件传入的参数。

Then I would like the form load and the 3 sort buttons on the form to call the function getFormRecs(), while passing in the arg, like 然后我想在加载arg时传递表单加载和表单上的3个排序按钮来调用函数getFormRecs()

getFormRecs('formload')
getformRecs('sorta')
getformRecs('sortb')
getformRecs('sortc')

I would define the correct sort field in the top of the function based on the arg passed in. 我将基于传入的arg在函数顶部定义正确的排序字段。

The end result is simply to reuse a function or Sub-routine that contains nearly identical long winded sql. 最终结果只是简单地重用了包含几乎相同的长条sql的函数或子例程。

This seems to be about what you're asking for: 这似乎与您要的内容有关:

Function getFormRecs(ByVal arg As String)
    getFormRecs = "sql ... " & _
                  "." & _
                  "." & _
                  "." & _
                  "order by " & arg
End Function
Private Sub Form_Load()
    Dim sql As String
    sql = getFormRecs("formload")
    '... Logic that uses sql
End Sub

I'm unsure why you need a function. 我不确定为什么需要一个功能。 You could start with a base query which does not include an ORDER BY . 您可以从不包含ORDER BY的基本查询开始。

SELECT id, fld2, fld3
FROM YourTable;

Then re-use that same query elsewhere by including it as the data source in a new SELECT statement where you add the specific ORDER BY you require. 然后,通过将其作为数据源包含在新的SELECT语句中,在其中添加所需的特定ORDER BY ,在其他地方重复使用该查询。

SELECT q.id, q.fld2, q.fld3
FROM qryBase AS q
ORDER BY q.fld3;

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

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