' ** Référence : Microsoft Excel 11.0 Library Objects ou équivalent
Sub SheetProtect(ByVal sBookAProteger As String, ByVal sFeuilleAProteger As String, ByVal vPassword As Object)
If My.Computer.FileSystem.FileExists(sBookAProteger) Then
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.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 My.Computer.FileSystem.FileExists(sBookADeproteger) Then
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.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