宏无法在Excel中的锁定工作表中找到单词

时间:2018-10-28 15:52:56

标签: excel vba excel-vba

我有一个代码,如果我找不到一个单词,它将显示一条消息,并关闭表格

代码可以正常工作,但是如果我在工作表上输入密码,它会一直说找不到单词

如果我删除密码,那么可以找到单词

搜索代码

Dim r As Range
Set r = Sheets("sheet1").Range("D:D").Find(What:="word", LookAt:=xlWhole, MatchCase:=False)
If r Is Nothing Then
  MsgBox "The word was not found"
End 'Closing the form
End If

密码

Dim wks1 As Worksheet
For Each wks1 In ActiveWorkbook.Worksheets
    wks1.Protect "1234", UserInterfaceOnly:=True, AllowSorting:=True, AllowFiltering:=True
    Next wks1

我很乐意为您解决问题提供帮助

如果我的问题不明白,请给我写信

2 个答案:

答案 0 :(得分:0)

这是一个有效的示例。

Sub test()
Dim ws As Worksheet
Dim pwd As String
Dim r As Range

pwd = "pippo"

For Each ws In Worksheets
    ws.Unprotect Password:=pwd
Next ws

Set r = Sheets("Foglio1").Range("D:D").Find(What:="word", LookAt:=xlWhole, MatchCase:=False)

If r Is Nothing Then
    MsgBox "parola non trovata"
Else
    MsgBox "parola trovata!"
End If

For Each ws In Worksheets
    ws.Protect Password:=pwd
Next ws

End Sub

希望对您有帮助。

答案 1 :(得分:0)

使用参数UserInterFaceOnly保护VBA中的工作表,然后VBA可以在受保护的工作表中找到该单词,甚至不允许选择受保护的单元格。

例如,在ThisWorkbook模块中使用

Private Sub Workbook_Open()
    For Each ws In Worksheets
        ws.Protect Password:="secret", DrawingObjects:=True, Contents:=True, Scenarios:=True, userinterfaceonly:=True
    Next ws

End Sub

然后,您无需先保护表即可运行代码。

Sub test()
Dim ws As Worksheet
Dim r As Range

Set r = Sheets("Sheet1").Range("A:D").Find(What:="word", LookAt:=xlWhole, MatchCase:=False)

If r Is Nothing Then
    MsgBox "not found"
Else
    MsgBox "found"
End If
End Sub

enter image description here