我怎样才能调用这个函数的填充我的访问形式列表控件(How can i call the below

2019-07-30 03:17发布

我需要从一个访问表填充表格的访问列表框中。

下面是按钮的单击事件,我复制粘贴的代码:

Public Sub PopulateLBWithData(DBPath As String, _
TableName As String, FieldName As String, _
oListControl As Object,Optional Distinct As Boolean = False, _
Optional OrderBy As String)

''#PURPOSE: Populate a list box, combo box
''#or control with similar interface with data
''#from one field in a Access Database table

''#Parameters: DBPath: FullPath to Database
''#TableName: The Name of the Table
''#FieldName: Name of the Field
''#Distinct: Optional -- True if you want distinct value
''#Order By:  Optional -- Field to Order Results by

''#Must have reference to DAO in your project

Dim sSQL As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim td As DAO.TableDef
Dim f As DAO.Field

Dim sTest As String
Dim bIsNumeric As Boolean
Dim i As Integer

On Error Resume Next

''#validate all parameters

oListControl.AddItem "a"
oListControl.Clear
If Err.Number > 0 Then Exit Sub

sTest = Dir(DBPath)
If sTest = "" Then Exit Sub

Set db = Workspaces(0).OpenDatabase(DBPath)
If Err.Number > 0 Then Exit Sub

Set td = db.TableDefs(TableName)
If Err.Number > 0 Then
    db.Close
    Exit Sub
End If

Set f = td.Fields(FieldName)
    If Err.Number > 0 Then
        db.Close
        Exit Sub
    End If

If Len(OrderBy) Then
    Set f = td.Fields(OrderBy)
    If Err.Number > 0 Then
        db.Close
        Exit Sub
    End If
End If

sSQL = "SELECT "
If Distinct Then sSQL = sSQL & "DISTINCT "
sSQL = sSQL & "[" & FieldName & "] FROM [" & TableName & "]"

If OrderBy <> "" Then sSQL = sSQL & " ORDER BY " & OrderBy

Set rs = db.OpenRecordSet(sSQL, dbOpenForwardOnly)

With rs
    Do While Not .EOF
        oListControl.AddItem rs(FieldName)
        .MoveNext
    Loop
    .Close
End With

db.Close
End Sub

不过这个功能根据VBA约定需要的参数。

请帮我,我怎么能调用这个函数来从同一个访问表填充我的VBA形式的列表框?

Answer 1:

该代码是为了什么,你可能想要做过于复杂。

为什么不尝试只设置控件的行源,然后重新查询。

如果你想保留的参数,然后传中,SQL。

Dim strSQL As String

strSQL = "SELECT MyField FROM MyTable;"

Me.lstMyListBox.RowSource = strSQL
Me.lstMyListBox.Requery


文章来源: How can i call the below function to populate my access form list control