数据validation列表与VBA数组

我正在尝试使用vba代码创build数据validation列表。 该数组根据许多variables生成自己。

这里是我正在使用的代码

For iter4 = 2 To nbWsheet If Wsheet.Cells(iter4, 2) = Cat And Wsheet.Cells(iter4, ColMod) = "x" And Wsheet.Cells(iter4, ColStd) = "oui" Then TableValue = Wsheet.Cells(iter4, 4).Value & " - " & Wsheet.Cells(iter4, 7).Value Table = Table & "," & TableValue End If Next iter4 'Ajout de la list With Cells(iGlob, 5).Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:=Table .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = "" .ShowError = "" End With 

这个代码的问题是表中的文本包含“,”。 当数据validation列表生成时,每次看到一个“,”它把文本在一个新的行…

有没有办法将“,”放在桌子里面

我想要显示的例子:123456 – 引擎,300HP

希望我清楚,

谢谢,

我不认为自定义列表中的逗号有一个转义字符。 根据MSDN Validation.Add ,逗号总是分开条目。

一种解决方法是使用dynamic命名范围。

  1. 在隐藏的表格或某个地方使用备用列,可以使用列A进行演示
  2. 在A1中,input“DV_ListTable”,定义名称为DV_ListTable的单元格
  3. 突出显示列A,将其定义为DV_ListColumn
  4. 使用名称pipe理器将另一个名称定义为带有RefersTo as的DV_List
    =OFFSET(DV_ListTable,1,0,IF(COUNTA(DV_ListColumn)-1=0,1,COUNTA(DV_ListColumn)-1))
    ResultingNameManager

现在数据validation将是(单元格D1):
DV

然后macros来改变这个dynamic范围的内容将是:

 Option Explicit Sub ChangeDataValidationList() Dim i As Long, Table As String, TableValue As String Dim oRng As Range, oValues As Variant With ThisWorkbook ' Build up the new table list Table = .Names("DV_ListTable").RefersToRange.Value ' Header ' For Demo, the data is from Columns next to the DV_ListTable Set oRng = .Names("DV_ListTable").RefersToRange.Offset(0, 1) Do Until IsEmpty(oRng) TableValue = oRng.Value & " - " & oRng.Offset(0, 1).Value Table = Table & vbCrLf & TableValue Set oRng = oRng.Offset(1, 0) Loop Set oRng = Nothing ' Clear the contents in the column .Names("DV_ListColumn").RefersToRange.ClearContents ' Paste in the values separated by vbCrLf oValues = Application.Transpose(Split(Table, vbCrLf)) .Names("DV_ListTable").RefersToRange.Resize(UBound(oValues)) = oValues Set oValues = Nothing End With End Sub 

“ChangeDataValisationList”执行后的示例截图:
截图

希望这可以帮助你在正确的方向工作。

用Chr(44)replace“,”。 Chr函数返回一个基于VBA字符代码的string。 当你想插入双引号(Chr(34)用于双引号)时,我发现它也派上用场。