在VBA中使用包含单引号数据的过滤器(Applying Filter in VBA with data including Single Quotes)

编程入门 行业动态 更新时间:2024-10-04 15:28:32
在VBA中使用包含单引号数据的过滤器(Applying Filter in VBA with data including Single Quotes)

我一直试图让一个简单的过滤器在一个表单上工作,在这个表单上应用基于Access DB中两列的过滤器。

Private Sub cmb_Name_AfterUpdate()  
Me.cmb_WorkCity.Requery  
DoCmd.ApplyFilter , "[Employee Name]='" & Me.cmb_Name.Column(0) & "' And [Movement Type]='" & Me.cmb_Name.Column(1) & "'"  
End Sub  
 

在当前测试数据中有两个实例,其中员工姓名具有单引号,例如O'Malley。 这会导致查询中出现“语法错误(缺少运算符)”

有关如何解决此问题的任何想法?

I've been trying to get a simple filter to work on a form where it applies filters based on two columns in my Access DB.

Private Sub cmb_Name_AfterUpdate()  
Me.cmb_WorkCity.Requery  
DoCmd.ApplyFilter , "[Employee Name]='" & Me.cmb_Name.Column(0) & "' And [Movement Type]='" & Me.cmb_Name.Column(1) & "'"  
End Sub  
 

There are two instances in the current test data where the Employee Name has a single quote e.g. O'Malley for instance. This results in a 'Syntax error (missing operator) in query

Any thoughts on how to resolve this issue?

最满意答案

使用Replace()替换员工姓名中每个单引号的两个单引号。

Private Sub cmb_Name_AfterUpdate()
Dim strFilter As String
Me.cmb_WorkCity.Requery
'DoCmd.ApplyFilter , "[Employee Name]='" & Me.cmb_Name.Column(0) & "' And [Movement Type]='" & Me.cmb_Name.Column(1) & "'"
strFilter = "[Employee Name]='" & Replace(Me.cmb_Name.Column(0), "'", "''") & _
    "' And [Movement Type]='" & Me.cmb_Name.Column(1) & "'"
Debug.Print strFilter ' <- view in Immediate window; Ctrl+g will take you there
DoCmd.ApplyFilter , strFilter
End Sub

Use Replace() to substitute two single quotes for each one single quote in employee name.

Private Sub cmb_Name_AfterUpdate()
Dim strFilter As String
Me.cmb_WorkCity.Requery
'DoCmd.ApplyFilter , "[Employee Name]='" & Me.cmb_Name.Column(0) & "' And [Movement Type]='" & Me.cmb_Name.Column(1) & "'"
strFilter = "[Employee Name]='" & Replace(Me.cmb_Name.Column(0), "'", "''") & _
    "' And [Movement Type]='" & Me.cmb_Name.Column(1) & "'"
Debug.Print strFilter ' <- view in Immediate window; Ctrl+g will take you there
DoCmd.ApplyFilter , strFilter
End Sub

                    
                     
          

更多推荐

本文发布于:2023-08-07 13:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464090.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   单引号   数据   Applying   VBA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!