简体   繁体   中英

Macro can not find a word in a locked sheet in Excel

I have a code that if I can not find a word, it displays a message, and closes the form

The code works fine, but if I put a password on the sheet, it says all the time that it does not find the word

If I remove the password, then yes the word finds

The code of the search

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

The password code

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

I would be happy for any help solve my problem

If my question is not understood please write to me

this is an example that works.

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

I hope this help you.

Protect the sheet in VBA with the parameter UserInterFaceOnly , then the VBA can find the word in a protected sheet that does not even allow selection of protected cells.

For example, in the ThisWorkbook module use

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

Then you can run the code without first unprotecting the sheet.

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM