2014-03-26 56 views
1

我有一些代碼可行,但我認爲可以寫得更好。我對此並不是很瞭解,但是有沒有辦法可以清理它?它通過與隱藏多個數據行上的單獨的片材,如果小區A12是< 40.清理重複的VBA代碼

Option Explicit 
Sub Main() 
Dim wsa As Worksheet: Set wsa = ActiveWorkbook.Sheets("Sheet A") 
Dim wse As Worksheet: Set wse = ActiveWorkbook.Sheets("Sheet E") 
Dim wsf As Worksheet: Set wsf = ActiveWorkbook.Sheets("Sheet F") 
Dim wsg As Worksheet: Set wsg = ActiveWorkbook.Sheets("Sheet G") 
Dim wsk As Worksheet: Set wsk = ActiveWorkbook.Sheets("Sheet K") 

    If wsa.Range("A12").Value < "40" Then 
    Range("A_Data").EntireRow.Hidden = True 
    Else 
    Range("A_Data").EntireRow.Hidden = False 
    End If 

    If wse.Range("A12").Value < "40" Then 
    Range("E_Data").EntireRow.Hidden = True 
    Else 
    Range("E_Data").EntireRow.Hidden = False 
    End If 

    If wsf.Range("A12").Value < "40" Then 
    Range("F_Data").EntireRow.Hidden = True 
    Else 
    Range("F_Data").EntireRow.Hidden = False 
    End If 

    If wsg.Range("A12").Value < "40" Then 
    Range("G_Data").EntireRow.Hidden = True 
    Else 
    Range("G_Data").EntireRow.Hidden = False 
    End If 

    If wsf.Range("A12").Value < "40" Then 
    Range("K_Data").EntireRow.Hidden = True 
    Else 
    Range("K_Data").EntireRow.Hidden = False 
    End If 

Exit Sub 

任何幫助將不勝感激,我有一個很難搞清楚了這一點。謝謝你的時間。

回答

1

我會做這一個:

Sub Main() 
    Dim x 
    For Each x In Array("A", "E", "F", "G", "K") 
     Range(x & "_Data").EntireRow.Hidden = _ 
      (CDbl(ActiveWorkbook.Worksheets("Sheet " & x).Range("A12").Value) < 40) 
    Next x 
End Sub 

我也用

CDbl(ActiveWorkbook.Worksheets("Sheet " & x).Range("A12").Value) < 40 

因爲字符串比較可能會給你帶來意想不到的結果(比如"2">"10"返回TRUE)。