简体   繁体   English

VBA excel保护表

[英]VBA excel protecting sheets

I created a spreadsheet where on Work Book Open Event i create a sheet called "Hello".我创建了一个电子表格,在工作簿打开事件中我创建了一个名为“Hello”的工作表。 This works perfectly fine.这工作得很好。 The problem arises when I Protect the structure of the WORKBOOK with password.当我使用密码保护 WORKBOOK 的结构时出现问题。 Now when i open my workbook and try to add the sheet to it, the application gives me an error on this line of code where I'm adding the sheet.现在,当我打开我的工作簿并尝试向其中添加工作表时,应用程序在我添加工作表的这行代码上给了我一个错误。 All my code below我所有的代码如下

 Private Sub Workbook_Open()
 Dim ws As Worksheet
 Dim i As Integer
 Dim isHELLOexist As Boolean
 isHELLOexist = False
 For i = 1 To Worksheets.Count
     If Worksheets(i).Name = "HELLO" Then
         isHELLOexist = True
     End If
 Next i

 If isHELLOexist = False Then
     Set ws = Sheets.Add '''here's where i get an error with ADDING sheet
     ws.Name = "HELLO"
 End If
 End Sub

Now this code works perfectly fine as long as STRUCTURE of workbook is not protected with password.现在只要工作簿的结构不受密码保护,此代码就可以正常工作。 What should i do here to get this to work?我应该怎么做才能让它发挥作用?

ERROR states:错误状态:

METHOD ADD OF OBJECT SHEETS FAILED ERROR 1004对象表的方法添加失败错误 1004

Figured it out....I first need to unprotect the workbook, add the sheet and protect it again like this...想通了......我首先需要取消保护工作簿,添加工作表并像这样再次保护它......

thisworkbook.unprotect("password")
If isHELLOexist = False Then
     Set ws = Sheets.Add '''here's where i get an error with ADDING sheet
     ws.Name = "HELLO"
End If
thisworkbook.protect("password"),true,true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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