[英]VBA to show/hide rows based on whether a cell's value is zero
我有一個Excel工作表,我想隱藏或取消隱藏某些行,具體取決於另一個單元格中的值。
簡而言之:
整個事情應該取決於單元格C2
, D2
, E2
。
如果C2
為空白,我希望隱藏第rows 31 to 40
,如果它不是空白 ,則需要顯示它們。
其他三個單元格相同,始終隱藏/取消隱藏以下10行:
D2 --> rows 41 to 50
E2 --> rows 51 to 60
我嘗試了這段代碼,但它沒有工作,我也沒有得到任何錯誤:
Sub Hide_rows()
If Range("LS!C2") = 0 Then
Rows("31:40").EntireRow.Hidden = True
Else
If Range("LS!D2") = 0 Then
Rows("41:50").EntireRow.Hidden = True
Else
If Range("LS!E2") = 0 Then
Rows("51:60").EntireRow.Hidden = True
Else
If Range("LS!C2") > 0 Then
Rows("31:40").EntireRow.Hidden = False
Else
If Range("LS!D2") > 0 Then
Rows("41:50").EntireRow.Hidden = False
Else
If Range("LS!E2") > 0 Then
Rows("51:60").EntireRow.Hidden = False
Else
End If
End If
End If
End If
End If
End If
End Sub
謝謝!
在我看來,你只需要以下幾行:
With Sheets("LS")
.Rows("31:40").EntireRow.Hidden = (.Range("C2") = 0)
.Rows("41:50").EntireRow.Hidden = (.Range("D2") = 0)
.Rows("51:60").EntireRow.Hidden = (.Range("E2") = 0)
End With
根據克里斯的觀點編輯 - 以下就足夠了:
With Sheets("LS")
.Rows("31:40").Hidden = (.Range("C2") = 0)
.Rows("41:50").Hidden = (.Range("D2") = 0)
.Rows("51:60").Hidden = (.Range("E2") = 0)
End With
將此Worksheet_Change事件驅動的子過程放在LS工作表的私有代碼表(右側clcik名稱選項卡,查看代碼)中,而不是在公共模塊代碼表中。
sub worksheet_change(byval Target as range)
if not intersect(target, range("C2:E2")) is nothing then
on error goto safe_exit
application.enableevents = false
rows("31:40").entirerow.hidden = isempty(cells(2, "C"))
rows("41:50").entirerow.hidden = isempty(cells(2, "D"))
rows("51:60").entirerow.hidden = isempty(cells(2, "E"))
end if
safe_exit:
application.enableevents = true
end sub
對C2:E2所做的任何更改都將觸發此子過程,並且將重新評估這些行的隱藏/未隱藏的性質。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.