MTNQ > 30-11-15, 01:34 AM
Function ProtectDoc(ByVal strDocPath As String, strPwd As String, blnProtect As Boolean) As Boolean
Dim wrdApp As Object
Dim wrdDoc As Object
Dim strFolderPath As String
Dim strFileName As String
Dim strFileType As String
Dim blnQuitApp As Boolean
Dim blnCloseDoc As Boolean
On Error Resume Next
If strDocPath = Trim(strDocPath) = "" Then Exit Function
strFolderPath = Left$(strDocPath, InStrRev(strDocPath, "\"))
strFileName = Mid$(strDocPath, Len(strFolderPath) + 1)
strFileType = Mid$(strFileName, InStrRev(strFileName, ".") + 1)
If strFolderPath = "" Or strFileName = "" Or strFileType = "" Then
MsgBox "Duong dan """ & strDocPath & """ khong dung", , "Loi"
Exit Function
End If
If strFileType <> "doc" And strFileType <> "docx" Then Exit Function
Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
Err.Clear
Set wrdApp = CreateObject("Word.Application"): blnQuitApp = True
Set wrdDoc = wrdApp.Documents.Open(strDocPath): blnCloseDoc = True
Else
Set wrdDoc = wrdApp.Documents(strFileName)
If Err.Number <> 0 Then
Err.Clear
Set wrdDoc = wrdApp.Documents.Open(strDocPath): blnCloseDoc = True
End If
End If
If Err.Number <> 0 Then GoTo ErrorHandler
On Error GoTo ErrorHandler
If blnProtect Then
If wrdDoc.ProtectionType = -1 Then wrdDoc.Protect 2, , strPwd: wrdDoc.Save
Else
If wrdDoc.ProtectionType <> -1 Then wrdDoc.Unprotect strPwd: wrdDoc.Save
End If
If (Not wrdDoc Is Nothing) And blnCloseDoc Then wrdDoc.Close True
ProtectDoc = True
Exit_ErrorHandler:
If Not wrdDoc Is Nothing Then Set wrdDoc = Nothing
If Not wrdApp Is Nothing Then
If blnQuitApp Then wrdApp.Quit
Set wrdApp = Nothing
End If
Exit Function
ErrorHandler:
ProtectDoc = False
Select Case Err.Number
Case 5174
MsgBox "Khong tim thay file: " & vbCrLf & strDocPath, , "Loi"
Case 5485
If blnCloseDoc Then wrdDoc.Close False
MsgBox "Mat khau: """ & strPwd & """ khong dung" & vbCrLf & strDocPath, , "Loi"
Case Else
MsgBox "File: """ & strDocPath & """" & vbCrLf & Err.Description, _
vbExclamation, "Error ProtectDoc: " & Err.Number
End Select
Err.Clear
GoTo Exit_ErrorHandler
End Function