2016-02-10 72 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