使用VBA在UserInterfaceOnly受保护的工作表上设置验证时,如何解决“运行时错误'1004'”?

时间:2019-08-13 11:54:15

标签: excel vba

当我尝试使用VBA在单元格上设置验证时,出现“运行时错误'1004':应用程序定义或对象定义的错误”。使用设置为true的UserInterFaceOnly标志保护工作表。

我尝试将特定功能/子移至空白工作簿,以查看错误是否再次发生,并且也没有保护措施以查看错误是否仍然有效。问题是相同的,并且如果工作表不受保护,则代码可以正常工作。我在问题上进行了搜索,发现下面的链接表明验证字符串有字符限制,但是即使将其限制为200个字符也不能解决问题。 https://answers.microsoft.com/en-us/msoffice/forum/all/what-is-limit-of-the-number-of-entries-in-excel/9ce4a909-8b03-428f-94a4-1b13433aa399

'pasting this code into a blank workbook, running ps and then running test should reproduce the problem
'set specific protection with pw
Sub ps()
    ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="secret"
    ThisWorkbook.Worksheets("Sheet1").Protect Password:="secret", UserInterFaceOnly:=True
End Sub

'general protection sub
Public Sub protectSht(ws As Worksheet, pass As String)
    ws.Protect Password:=pass, UserInterFaceOnly:=True
End Sub

'set validation on cells
Sub setValidation(rng As Range, lst As Collection)
    Dim tmpstr As String
    Dim loopVar As Variant

    For Each loopVar In lst
            tmpstr = Trim(loopVar) & ", " & tmpstr
    Next loopVar

    If lst.Count = 0 Then
        rng.Validation.Delete
    Else
        With rng.Validation
        .Delete
        .Add xlValidateList, AlertStyle:=xlValidAlertStop, _
             Operator:=xlBetween, Formula1:=tmpstr
        End With
    End If
End Sub

'test function reproducing error
'run this on a sheet that's protected using ps
Sub test()
    Dim tst As New Collection
    tst.Add "hello"
    tst.Add "bye"
    tst.Add "etc"
    setValidation ThisWorkbook.Sheets(1).Range("B1:B5"), tst
End Sub

这应该在单元格上设置验证,但是无论它们是否被锁定都不会成功。而是显示“运行时错误'1004':应用程序定义或对象定义的错误”。

0 个答案:

没有答案