如何从Access窗体上单击按钮调用此子例程



所以,这个问题很愚蠢,但我想不通。我有下面的代码来搜索文件路径名,我相信它会将记录添加到表中(未经测试)。但是,问题是我无法调用这个子程序。我希望能够点击表单上的按钮并运行。有人知道我是怎么做的吗?非常感谢。

Public Function SelectFile() As String
Dim f As FileDialog
Set f = Application.FileDialog(msoFileDialogOpen)
With f
.AllowMultiSelect = False
.Title = "Please select file to attach"
If .Show = True Then
SelectFile = .SelectedItems(1)
Else
Exit Function
End If
End With
Set f = Nothing
End Function

Public Sub AddAttachment(ByRef rstCurrent As DAO.Recordset, ByVal strFieldName As String, ByVal strFilePath As String)
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
'Ask the user for the file
Dim filepath As String
filepath = SelectFile()
'Check that the user selected something
If Len(filepath) = 0 Then
Debug.Assert "No file selected!"
Exit Sub
End If
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset("Table1")
''''change this
'Add a new row and an attachment
rst.AddNew
AddAttachment rst, "Files", filepath
rst.Update
'Close the recordset
rst.Close
Set rst = Nothing
Set dbs = Nothing
End Sub

您可以向有问题的按钮添加一个事件过程:

  1. 在表单设计模式中,单击按钮
  2. 在属性表中,选择单击事件的生成器[…]按钮
  3. 您将转到VBA编辑器。输入如下代码:

    Private Sub cmdAddAttachment_Click() AddAttachment Nothing, "", "" End Sub

也就是说,您的AddAttachment例程有一个明显的无限循环。线路:

AddAttachment rst, "Files", filepath

似乎并没有实际填充任何字段值。事实上,代码中没有使用变量rstCurrentstrFieldNamestrFilePath。您可能需要调试此例程,然后它才能工作。