如何:设置和清除工作簿密码
创建一个密码可以限制对工作簿的访问。 下面的示例设置工作簿的密码。 若要清除密码,请将密码设置为空字符串。
**适用于:**本主题中的信息适用于 Excel 2007 和 Excel 2010 的文档级项目和应用程序级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能。
在文档级自定义项中设置密码
设置密码
将 ThisWorkbook 的密码属性设置为由用户提供的字符串。
Private Sub SetPassword() Dim password As String Dim confirmPassword As String password = Me.Application.InputBox("Enter the new password:").ToString() confirmPassword = Me.Application.InputBox("Confirm the password:").ToString() If password <> confirmPassword Then MessageBox.Show("The passwords you typed do not match.") Globals.ThisWorkbook.Password = "" Else Globals.ThisWorkbook.Password = password End If End Sub
private void SetPassword() { string password = this.Application.InputBox("Enter the new password:", missing, missing, missing, missing, missing, missing, missing).ToString(); string confirmPassword = this.Application.InputBox("Confirm the password:", missing, missing, missing, missing, missing, missing, missing).ToString(); if (password != confirmPassword) { MessageBox.Show("The passwords you typed do not match."); Globals.ThisWorkbook.Password = ""; } else { Globals.ThisWorkbook.Password = password; } }
在应用程序级外接程序中设置密码
为活动工作簿设置密码
将 Microsoft.Office.Interop.Excel._Workbook 类的 Password 属性设置为用户提供的字符串。 若要使用此示例,请从项目内的 ThisAddIn 类中运行代码。
Private Sub SetPassword() Dim password As String Dim confirmPassword As String password = Me.Application.InputBox("Enter the new password:").ToString() confirmPassword = Me.Application.InputBox("Confirm the password:").ToString() If password <> confirmPassword Then System.Windows.Forms.MessageBox.Show("The passwords you typed do not match.") Me.Application.ActiveWorkbook.Password = "" Else Me.Application.ActiveWorkbook.Password = password End If End Sub
private void SetPassword() { string password = this.Application.InputBox("Enter the new password:", missing, missing, missing, missing, missing, missing, missing).ToString(); string confirmPassword = this.Application.InputBox("Confirm the password:", missing, missing, missing, missing, missing, missing, missing).ToString(); if (password != confirmPassword) { System.Windows.Forms.MessageBox.Show ("The passwords you typed do not match."); this.Application.ActiveWorkbook.Password = ""; } else { this.Application.ActiveWorkbook.Password = password; } }