【问题标题】:How to add an item to a combobox (using AddItem()) which contains a semicolon?如何将项目添加到包含分号的组合框(使用 AddItem())?
【发布时间】:2020-02-01 05:41:18
【问题描述】:

我在 Access 表单上有一个多列组合框(Access 2019 x64,如果这很重要),我想使用它的 AddItem() 方法来填充它,如 in this documentation 所述。引用它:

对于多列列表,使用分号分隔字符串 每列(例如,“1010;red;large”对于三列列表)。 如果 Item 参数包含的字符串少于 控件,将从最左侧的列开始添加项目。如果 Item 参数包含的字符串多于控件中的列, 多余的字符串将被忽略。

那么当字符串本身已经包含分号的情况下,不可能为某个列添加字符串?

【问题讨论】:

    标签: vba ms-access combobox


    【解决方案1】:

    将包含分号的列值用双引号括起来,例如:

    AddItem """Column1;A"";Column2;Column3"
    

    将产生:

    +-----------+---------+---------+
    | Column1;A | Column2 | Column3 |
    +-----------+---------+---------+
    

    【讨论】:

    • 谢谢,加 1 并接受。你到底是怎么获得这些知识的?我在文档中找不到任何关于它的信息。此外,如果我们在该字符串中有分号 双引号,它会提出一个问题。我会尝试学习......我的实际目标是拥有一个“编码”任意字符串的函数,以便它可以用作列值。
    • 不客气。我使用 MS 访问控制向导对其进行了逆向工程:创建了一个组合框,指定了一个值列表,输入了一些包含分号的值,然后检查了生成的属性字符串。
    【解决方案2】:

    所有功劳归于@Lee Mac,他完全回答了我最初的问题。然而,答案立即提出了我们应该如何处理已经包含引号的字符串的问题。

    因此,我在 VBA 中编写了以下函数,似乎可以完全解决问题。 cmets 应该是不言自明的。如果您发现错误,请发表评论。

    我已将此作为单独的答案发布,因为评论太长了,而且社区似乎不喜欢将此类答案编辑到原始问题中。

    'Notes:
    '
    'The following function quotes an arbitrary string so that it can be
    'used as part of the parameter to the ComboBox.AddItem() method.
    'Writing that function was necessary because there is no easy way to
    'use strings which already contain the ; character as part of that
    'parameter, or which even contain the ; character as well as double
    'quotes; see also Microsoft's documentation.
    '
    'To construct the parameter for the AddItem() method, the following
    'must be done:
    '
    'For EACH column, the source string must be quoted using the following
    'function. Then, all QUOTED strings must be concatenated, separating
    'them only by one ; character.
    '
    'Successfully tested 2019-10-03 in Access 2019 / 64-bit / VBA with a
    'standard combobox on a form.
    
    Public Function QuoteStringForValueList(sString As String) As String
    
      Dim sTemp As String, sDDQ As String
    
      'String containing two double quotes to make reading easier
      sDDQ = Chr(34) & Chr(34)
    
      'Replace each double quote by four double quotes
      sTemp = Replace(sString, Chr(34), sDDQ & sDDQ)
    
      'Add two leading and two trailing double quotes
      QuoteStringForValueList = sDDQ & sTemp & sDDQ
    
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多