vba - 运行时错误“1004”应用程序定义或对象定义错误:字符串变量作为数据验证公式
问题描述
所以,我是 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
解决方案
我尝试了您的代码(进行了一些小的更新以使其在我的 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
推荐阅读
- c - 无法以编程方式启动 Linux TAP 设备
- c# - Jetbrains Rider 无法解决符号 ServiceCollection
- python - 无效的参数/选项 - '|'
- git - bitbucket 连接失败
- javascript - 如果我需要添加更多卡片,如何使我的卡片独立,同时使代码可扩展?
- php - 如何在laravel网站上传视频并保存和列表
- python - Python pad list 是下一个乘数 6 的大小
- html - jQuery:小标签字体大小,如果字段不为空
- react-native - Redux-undo 在发布 apk 中返回未定义?
- python - 在Python中用空格对列表中的数字求和