清理重复的VBA代码

时间:2014-03-26 21:13:06

标签: excel vba excel-vba

我有一些有效的代码,但我认为可以写得更好。我对此并不十分了解,但有没有办法可以清理它?如果单元格A12 <1,则它在单独的纸张上通过并隐藏更多数据的行。 40。

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 个答案:

答案 0 :(得分: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)。