2016-02-04 112 views
1

我正在尝试使用vba代码创建数据验证列表。该数组根据许多变量生成自身。使用vba数组验证列表

这里是我使用

  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 

这段代码的问题的代码,是在表中的文本包含“”。当生成的数据验证列表,每次都看到“”它把文本在新行...

有没有一种方法,以保持“”表

为例内我想显示:123456 - 发动机,300马力

希望我是清楚的,

感谢,

+0

你几乎清楚...但你能显示你尝试使用的数据吗?可能是一个截图。 –

+0

我知道这样做的唯一方法是将您的列表输出到一个单元格区域,然后设置Formula1以引用该单元格区域。您可以隐藏单元格,或将其放入隐藏的工作表中。 – tigeravatar

+0

查看[这里](http://stackoverflow.com/questions/30724178/create-data-validation-list-when-some-of-the-values-have-commas)为同一个问题和一些创新的答案。 – tigeravatar

回答

0

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

+0

这仍然会导致被问到相同的问题。OP的数据需要在下拉列表的单行中,但该数据包含一个逗号(例如:'123456 - Engine,300HP')。但是,逗号会导致验证列表将条目拆分为两个('123456 - Engine'和'300HP',当它应该是单个条目时,用'Chr(44)'替换逗号将导致同样的问题。这不会回答或解决问题。 – tigeravatar

2

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

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

  1. 在隐藏工作表中使用备用列或某个地方,让使用列用于演示
  2. 在A1,放在 “DV_ListTable”,名称为DV_ListTable
  3. 选中A列定义单元格,把它定义为DV_ListColumn
  4. 定义使用名称管理器作为DV_List与引用关联另一名
    =OFFSET(DV_ListTable,1,0,IF(COUNTA(DV_ListColumn)-1=0,1,COUNTA(DV_ListColumn)-1))
    ResultingNameManager

现在数据有效性将(细胞D1):
DV

然后宏改变该动态范围的内容将是:

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” 后执行:
screenshot

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