需要有关在 MS ACCESS 中使用 SQL 和 VBA 运行查询的建议

问题描述

请不要问问题,这是一个漫长而复杂的故事:-)

我只需要 sql 字符串中 Me.frmButtons.Form.Button01.caption 的正确语法(带所有引号)。谢谢。这个不行:

Private Sub Button01_Click()
             
Dim strsql As String
            
strsql = "SELECT * FROM table01 WHERE fldName = ""Me.bForm.Form.Button01.caption""    
ORDER BY FldName"

Me.mForm.Form.RecordSource = strsql
Me.mForm.Form.Requery
                
End Sub

解决方法

在 VBA 中,SQL 是字符串,而不是变量和对象,因此必须将这些对象连接到字符串,连接字符串的字符是“&”

SQL语句应该是这样的:

strsql = "SELECT * FROM table01 WHERE fldName = '" & Me.bForm.Form.Button01.caption & "' ORDER BY FldName"
,

这应该有效:

Private Sub Button01_Click()
             
    Dim strsql As String
            
    strsql = "SELECT * FROM table01 " & _
    "WHERE fldName = '" & Me!bForm.Form!Button01.Caption & "' " & _
    "ORDER BY FldName"
    Me!mForm.Form.RecordSource = strsql
                
End Sub

另外,你应该给按钮起有意义的名字。