【问题标题】:Excel VBA Data validation VBA Runtime Error 1004 “Application-defined or Object-defined error”Excel VBA 数据验证 VBA 运行时错误 1004 “应用程序定义或对象定义错误”
【发布时间】:2017-09-14 10:32:40
【问题描述】:

我在这里缺少什么?代码应该像单次执行一样工作,也可以在循环中工作。

Public mySheet As Worksheet
Set mySheet= Sheets("CARS")

此行出现错误-->

   .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Join(optionList, ",")

错误是-->

VBA 运行时错误 1004 “应用程序定义或对象定义错误

Public Function addDataValidation(row As Long)

Dim optionList(2) As String

optionList(0) = "1"
optionList(1) = "2"
optionList(2) = "3"

    With mySheet.Cells(row, 3).Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=Join(optionList, ",")
    End With

   With mySheet.Cells(row, 3).FormatConditions.Add(xlCellValue, xlEqual, "=1")
        .Font.Bold = True
        .Interior.ColorIndex = 4
        .StopIfTrue = False
    End With

    With mySheet.Cells(row, 3).FormatConditions.Add(xlCellValue, xlEqual, "=2")
        .Font.Bold = True
        .Interior.ColorIndex = 6
        .StopIfTrue = False
    End With

    With mySheet.Cells(row, 3).FormatConditions.Add(xlCellValue, xlEqual, "=3")
        .Font.Bold = True
        .Interior.ColorIndex = 3
        .StopIfTrue = False
    End With

    With mySheet.Cells(row, 3)
            .HorizontalAlignment = xlCenter
            .Value = optionList(0)
    End With

End Function

不合逻辑行为的原因是该函数与不同类模块中的同名函数混淆了。

解是 1

Private Function addDataValidation(row As Long)

解决方案 2

Check always cells protection status.

【问题讨论】:

  • 你在哪里设置mySheet
  • 更新了我的问题。
  • 仍然没有告诉我们您在哪里获得资格mySheet。它在一个模块中吗?您的 UDF 是否在同一个模块中?
  • 原因是我在不同的类模块中使用了同样命名的方法。我将我的功能从公共更改为私人,这解决了这个问题。非常感谢。你让我开心。
  • 不知道我是否添加了任何东西来解决您的问题,但很高兴它有帮助:)

标签: excel vba validation


【解决方案1】:

对我来说,如果 Excel 窗口最小化 (ThisWorkbook.Windows(1).WindowState = xlMinimized),此行可能会失败并出现指定错误,就像尝试 freeze panes 时一样。

我最终创建了一个辅助子例程:

Private Sub EnsureNotMinimized() ' #ILoveVBA
    If ThisWorkbook.Windows(1).WindowState = xlMinimized Then
        MsgBox "...", vbExclamation + vbOKOnly, msgBoxTitle
        ThisWorkbook.Windows(1).WindowState = xlMaximized
    End If
End Sub

并将其调用散布在代码库中...

【讨论】:

    【解决方案2】:

    在创建输入消息作为单元格数据验证的一部分时,我刚刚在使用 VBA 时遇到了相同的 1004 错误。就我而言,我试图添加一条长消息,输入消息限制为 255 个字符。任何更长的时间都会导致 1004 错误。

    解决方案是检查我的消息长度,如果超过 255 个字符则截断

        if len(my_message) > 255 then
           my_message = left(my_message,250) & "..."
        end if
    

    这修复了我的 1004 错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多