1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| Sub SheetProtect(ByVal sBookAProteger As String, ByVal sFeuilleAProteger As String, ByVal vPassword As Object)
If Dir(sBookAProteger) <> "" Then
Dim xlApp As Excel.Application
Dim xlBook As Workbook
Dim i As Integer
xlApp = CreateObject("Excel.Application")
xlBook = xlApp.Workbooks.Open(sBookAProteger)
For i = 1 To xlBook.Sheets.Count
If xlBook.Sheets(i).Name = sFeuilleAProteger Then
xlBook.Activate()
xlBook.Sheets(sFeuilleAProteger).Select()
xlBook.Worksheets(sFeuilleAProteger).Protect(vPassword)
Exit For
ElseIf i = xlBook.Sheets.Count Then
MsgBox("La feuille à protéger n'existe pas!", vbCritical)
End If
Next ixlBook.Close(True)
xlApp.Quit()
xlBook = Nothing
xlApp = Nothing
Else
MsgBox("Le fichier n'existe pas, vérifier le chemin !", vbCritical)
End If
End Sub
Sub SheetUnprotect(ByVal sBookADeproteger As String, ByVal sFeuilleADeproteger As String, ByVal vPassword As Object)
If Dir(sBookADeproteger) <> "" Then
Dim xlApp As Excel.Application
Dim xlBook As Workbook
Dim i As Integer
xlApp = CreateObject("Excel.Application")
xlBook = xlApp.Workbooks.Open(sBookADeproteger)
For i = 1 To xlBook.Sheets.Count
If xlBook.Sheets(i).Name = sFeuilleADeproteger Then
xlBook.Activate()
xlBook.Sheets(sFeuilleADeproteger).Select()
xlBook.Worksheets(sFeuilleADeproteger).Unprotect(vPassword)
Exit For
ElseIf i = xlBook.Sheets.Count Then
MsgBox("La feuille à déprotéger n'existe pas!", vbCritical)
End If
Next ixlBook.Close(True)
xlApp.Quit()
xlBook = Nothing
xlApp = Nothing
Else
MsgBox("Le fichier n'existe pas, vérifier le chemin !", vbCritical)
End If
End Sub
'Exemple d'utilisation
Private Sub Button1__Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Protéger
Call SheetProtect("C:\Classeur1.xls", "Feuil2", 1206)
'Déprotéger
Call SheetUnprotect("C:\Classeur1.xls", "Feuil2", 1206)
End Sub |
Partager