如何向包含分号的组合框(使用AddItem())添加项目?

问题描述 投票:2回答:2

我在Access表单上有一个多列组合框(如果重要,请访问Access 2019 x64),并希望使用其AddItem()方法来填充它,如in this documentation所述。引用:

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

因此,当字符串本身已经包含分号时,不可能为特定列添加字符串?

ms-access combobox access-vba
2个回答
3
投票

用双引号括住包含分号的列值,例如:

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

将产生收益:

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

0
投票

所有学分归@Lee Mac,他完全回答了我的原始问题。但是,答案立即提出了一个问题,即我们应该如何处理已经带有引号的字符串。

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

我将其作为单独的答案发布,因为评论的时间太长了,并且因为社区似乎不喜欢将这些答案编辑成原始问题。

'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 that parameter, 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, seperating
'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)

  'Surround by two double quotes at each side
  QuoteStringForValueList = sDDQ & sTemp & sDDQ

End Function
© www.soinside.com 2019 - 2024. All rights reserved.