在未受保护和受保护的工作表中实现代码VBA Excel

时间:2017-08-08 08:07:31

标签: excel vba excel-vba

当我尝试执行此代码时,它只执行Exit Sub之后的部分,当工作表不受保护时,只执行foreach循环。我认为这是由Exit Sub引起的。我的问题是,当工作表受到保护(for each cell in Range("B6:B112..))时,我希望执行不同的代码,而当工作表不受保护时,我希望执行另一个代码(从Dim rng as Range开始...)。我试过了If..Then..Else,但这不起作用。

Private Sub Worksheet_Change(ByVal Target As Range)
If Worksheets("test").ProtectContents Then Exit Sub

 For Each cell In Range("B6:B112")
 If cell.Value <> "" Then
 cell.EntireRow.Hidden = False
 Else
 cell.EntireRow.Hidden = True
 End If
 Next cell

 Dim rng As Range
 Dim eingabeNr As Double, letzteZeile As Long, eingabeDatum As String, eingabeNrString As String
 Set rng = Range("D:BC")

THX。

1 个答案:

答案 0 :(得分:0)

Private Sub Worksheet_Change(ByVal Target As Range)
If Worksheets("test").ProtectContents = True Then 'added = true for readability.

   For Each cell In Range("B6:B112")
       If cell.Value <> "" Then
           cell.EntireRow.Hidden = False
       Else
           cell.EntireRow.Hidden = True
       End If
   Next cell
Else
   Dim rng As Range
   Dim eingabeNr As Double, letzteZeile As Long, eingabeDatum As String,_
   eingabeNrString As String
   Set rng = Range("D:BC")

   Do some stuff here

End if