我正在使用VBA代码根据单元格的值来隐藏一些行。
Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Activate
If Not Application.Intersect(Range("K3"), Range(Target.Address)) Is Nothing Then
Select Case Target.Value
Case Is = "Full_FC_powered": Rows("33:33").EntireRow.Hidden = True
Rows("37:38").EntireRow.Hidden = True
Rows("45:46").EntireRow.Hidden = True
Case Is = "FC_for_hotel": Rows("33:33").EntireRow.Hidden = False
Rows("37:38").EntireRow.Hidden = False
Rows("45:46").EntireRow.Hidden = False
Case Is = "DG_for_transit": Rows("33:33").EntireRow.Hidden = False
Rows("37:38").EntireRow.Hidden = False
Rows("45:46").EntireRow.Hidden = False
End Select
End If
End Sub
代码本身已经可以工作,但有一个缺点:"K3 "的值被链接到另一个工作表,在那里它被计算。然而,如果K3的值在另一个工作表中发生变化,VBA代码就不能自动工作。我必须首先进入单元格K3并按回车键。
我的问题是:有没有办法将这段代码直接链接到另一个工作表,或者当单元格的值发生变化时刷新这段代码?
先谢谢你
细胞 I3
在K3中的公式是:......。=I3
.
必须使用这三个代码才能正常工作。调整 Sheet1
在 Public Const TargetSheet As String = "Sheet1"
适当的。
标准模块代码,如:模块1
Option Explicit
Public TargetValue As String
Public Const TargetCell As String = "K3"
Public Const TargetSheet As String = "Sheet1"
Sub HideShowRows(Sheet As Worksheet)
Dim rng As Range
With Sheet
Set rng = Union(.Rows("33"), .Rows("37:38"), .Rows("45:46"))
Select Case .Range(TargetCell).Value
Case "Full_FC_powered": rng.EntireRow.Hidden = True
Case "FC_for_hotel", "DG_for_transit": rng.EntireRow.Hidden = False
End Select
TargetValue = .Range(TargetCell).Value
End With
End Sub
本作业本代码
Option Explicit
Private Sub Workbook_Open()
TargetValue = Worksheets(TargetSheet).Range(TargetCell).Value
HideShowRows Worksheets(TargetSheet)
End Sub
纸张代码,例如:Sheet1
Option Explicit
Private Sub Worksheet_Calculate()
If Range(TargetCell).Value <> TargetValue Then
HideShowRows Me
End If
End Sub
' The following in this case are the same:
' If Range(TargetCell).Value <> TargetValue Then
' HideShowRows Me
' End If
' If Worksheets(TargetSheet).Range(TargetCell).Value <> TargetValue Then
' HideShowRows Worksheet(TargetSheet)
' End If