因此,我是VBA的新手,正在努力获取下拉列表以显示我使用的逗号分隔变量字符串中的项目。我想让给定列中的每个值在下拉列表中显示为选项。我确信它远非最有效的方法,但我一直在遍历列中的每个值,将其添加到字符串中,直到达到第一个空白值。我已经确认变量FilterListString已使用我希望它以正确格式的值填充,但是当我将其作为验证公式传递时,它会出错。我该如何解决?
谢谢!
If FilterColumn.Value <> "" Then
Do While Not IsEmpty(FilterColumn) 'Loop through values in the Filter column until blank
FilterListString = FilterListString & "," & FilterColumn.Value ' Supplement the Formula String
Set FilterColumn = FilterColumn.Offset(1, 0) 'Move down Row
Loop
Else
FilterListString = " " 'If inital cell is null set to blank
End If
With Sheets("Report Generation").Range("E" & ColumnNumber + 7).Validation 'Create Drop down List on the cell for filtering
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=FilterListString
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
答案 0 :(得分:0)
我尝试了您的代码(进行了较小的更新,使其可以在我的PC上运行),并且该代码可以正常运行。我最好的猜测是,该错误与工作表中的特定值(FilterColumn
值或经过目标验证的单元格)有关。
如果您在新工作簿中执行以下代码,则它应该提供所需的结果。
Option Explicit
Sub a()
Dim FilterColumn As Range
Dim FilterListString As String
Dim ColumnNumber As Integer
Set FilterColumn = Sheets(1).Range("A1")
FilterListString = "asd"
ColumnNumber = 1
''' testing values
Sheets(1).Range("A1").Value = "qqq"
Sheets(1).Range("A2").Value = 123
Sheets(1).Range("A1").Value = "www"
If FilterColumn.Value <> "" Then
Do While Not IsEmpty(FilterColumn) 'Loop through values in the Filter column until blank
FilterListString = FilterListString & "," & FilterColumn.Value ' Supplement the Formula String
Set FilterColumn = FilterColumn.Offset(1, 0) 'Move down Row
Loop
Else
FilterListString = " " 'If inital cell is null set to blank
End If
If ThisWorkbook.Worksheets.Count < 2 Then
Worksheets.Add
End If
With Sheets(2).Range("E" & ColumnNumber + 7).Validation 'Create Drop down List on the cell for filtering
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=FilterListString
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub