如何通过单击Access窗体上的按钮来调用此子例程?

时间:2016-05-23 19:07:51

标签: access-vba 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 个答案:

答案 0 :(得分:0)

您可以向相关按钮添加一个事件过程:

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

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

  5. 那就是说,你的AddAttachment例程有一个明显的无限循环。这一行:

    AddAttachment rst, "Files", filepath
    

    似乎没有真正填写任何字段值。实际上,代码中未使用变量rstCurrentstrFieldNamestrFilePath。您可能需要在它运行之前调试此例程。