2016-02-10 139 views
0

[问题1]我有一些VBA命令使Excel中的工作表名为“MS1”执行一系列任务。下面的一些例子:在Excel VBA中提高代码的可读性和速度

Sheets("MS1").Unprotect Password:="0123" 
Sheets("MS1").Visible = xlSheetVisible 
Sheets("MS1").OLEObjects("label1").Object.Caption = "this is label 1" 
Sheets("MS1").Select 
    Range("A1").Value = "Hello" 
Sheets("MS1").Protect Password:="0123" 

[问题1]我想更简明的代码通过避免“表(” MS1“)”的重复,以便提高可读性和处理速度。请随时展示解决方案。


[问题2]通过探索代码的可读性...

Option explicit 

    ActiveWorkbook.Unprotect Password:="0123" 

    Dim R As Variant 
    Dim CONJ3 As Variant 

    With Worksheets("MS2") 
    .Unprotect Password:="4567" 
    .Range("K12").Value = R 
    .Protect Password:="4567", UserInterfaceOnly:=True, AllowFiltering:=True 
    End with 

    CONJ3 = Array("Jan " & R, "Feb " & R, "Mar " & R, "Apr " & R, _ 
     "Mai " & R, "Jun " & R, "Jul " & R, "Aug " & R, "Set " & R, _  
     "Oct " & R, "Nov " & R, _"Dec " & R, "MS3", "MS4", "MS5") 

    With Worksheets("CONJ3") 
    .Unprotect Password:="4567" 
    .Visible = xlSheetVeryHidden 
    .Protect Password:="4567", UserInterfaceOnly:=True, AllowFiltering:=True 
    End With 

[问题2]我现在有一些问题,运行时error9:下标越界(可能的数组错误)。如何解决它?

回答

2

A With ... End With statement可用于提供单亲工作表参考,其中With ... End With块中的所有方法和属性均可使用前缀周期(也称为句号)进行引用。

With Worksheets("MS1") 
    .Unprotect Password:="0123" 
    .Visible = xlSheetVisible 
    '.OLEObjects("label1").Object.Caption = "this is label 1" 
    With .Range("A1") 
     .Value = "Hello" 
     .Interior.Color = vbYellow 
    End With 
    .Protect Password:="0123" 
    .Activate 'bring to the foreground 
End With 

这也改进了代码执行,因为携带单个引用而不是重复请求来建立父级工作表。

嵌套的With ... End With语句将接下来的两个命令隔离到单个单元格。这可能是单个单元格或一系列单元格。

+0

很好。谢谢@Jeeped! –

+1

YW。我真的没有得到倒票或VTC。可能有几种不同的方法来改善事情,但最明显的是'With ... End With'。在我的估计中,既不太宽泛,也不是基于意见。 – Jeeped

+0

我现在遇到数组问题:)在互联网上发现了几个例子,改编了它们,但没有为我的具体需要工作 –

0

下面的代码解决了[问题2]。现在我可以一次修改几个方面,只能在选定的工作表中进行修改:

Option explicit 

Sub Testing() 

ActiveWorkbook.Unprotect Password:="0123" 

    Dim R As Variant 
    Dim CONJ3 As Worksheet 

    With Worksheets("MS2") 
    .Unprotect Password:="4567" 
    .Range("K12").Value = R 
    .Protect Password:="4567", UserInterfaceOnly:=True, AllowFiltering:=True 
    End with 

For Each CONJ3 In ActiveWorkbook.Worksheets 
     Select Case CONJ3.Name 
     Case Is = "Jan " & R, "Feb " & R, "Mar " & R, "Apr " & R, _ 
     "Mai " & R, "Jun " & R, "Jul " & R, "Aug " & R, "Set " & R, _ 
     "Oct " & R, "Nov " & R, "Dec " & R, "MS3", "MS4", "MS5" 

    With CONJ3 
    .Unprotect Password:="4567" 
    .Visible = xlSheetVeryHidden 
    .Protect Password:="4567", UserInterfaceOnly:=True, AllowFiltering:=True 
    End With 

    Case Else 
    End Select 
    Next CONJ3 

ActiveWorkbook.Protect Password:="0123", Structure:=True, Windows:=False 

End Sub