首页 > 解决方案 > 运行时错误“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

标签: vbavalidation

解决方案


我尝试了您的代码(进行了一些小的更新以使其在我的 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

推荐阅读