如果将某列中的任何单元格选择为“是”,我需要激活Excel中的工作表,但是我的VBA代码不会粘贴-足够简单地对一个单元格进行操作,但是整列都让我失望。单元格是一个下拉列表,仅包含选项“是”或“否”
当前正在尝试:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$H$11:$H$23" Then
If ActiveWorkbook.Worksheets("Sheet1").Range("H11:H23").Value = "Yes" Then
Sheets("Sheet2").Visible = True
Else
Sheets("Sheet2").Visible = False
End If
End If
End Sub
有什么提示吗?谢谢
答案 0 :(得分:2)
一种更简单的不循环的解决方案是使用WorksheetFunction.CountIf method对Yes
进行计数。
如果至少一个单元格具有Sheet2
,请使用以下内容显示Yes
。
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim TestRange As Range
Set TestRange = Me.Range("H11:H23")
If Not Application.Intersect(Target, TestRange) Is Nothing Then 'if target is in test range
If Application.WorksheetFunction.CountIf(TestRange, "Yes") > 0 Then
Worksheets("Sheet2").Visible = True
Else
Worksheets("Sheet2").Visible = False
End If
End If
End Sub
如果测试范围内的所有单元格需要为Yes
,则将其更改为
If Application.WorksheetFunction.CountIf(TestRange, "Yes") = TestRange.Cells.Count Then
答案 1 :(得分:1)
我认为您可以尝试:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range, rng As Range
Dim Inrng As Boolean
If Not Intersect(Target, Me.Range("H11:H23")) Is Nothing Then
'Set a boolean variable to false
Inrng = False
'Set a range to loop
Set rng = Me.Range("H11:H23")
'Start looping the range
For Each cell In rng
'Convert the value of a cell to Upper case to avoid case sensitive issues
If UCase(cell.Value) = "YES" Then
'Turn the variable to true if value appears in the range
Inrng = True
'Exit the loop to avoid time consuming
Exit For
End If
Next cell
If Inrng = True Then
Worksheets("Sheet2").Visible = True
Else
Worksheets("Sheet2").Visible = False
End If
End If
End Sub