Excel 当我有两个条件时宏不工作
我试图创建一个跟踪器,当从下拉列表中选择“按时关闭”或“延迟关闭”时,它会自动隐藏整行。我目前正在使用下面的代码,已关闭的后期工作,但未关闭的时间。有人能帮忙吗Excel 当我有两个条件时宏不工作,excel,vba,if-statement,Excel,Vba,If Statement,我试图创建一个跟踪器,当从下拉列表中选择“按时关闭”或“延迟关闭”时,它会自动隐藏整行。我目前正在使用下面的代码,已关闭的后期工作,但未关闭的时间。有人能帮忙吗 Private Sub Worksheet_Change(ByVal Target As Range) BeginRow = 3 EndRow = 700 ChkCol = 14 For RowCnt = BeginRow To EndRow If (Cells(RowCnt, ChkC
Private Sub Worksheet_Change(ByVal Target As Range)
BeginRow = 3
EndRow = 700
ChkCol = 14
For RowCnt = BeginRow To EndRow
If (Cells(RowCnt, ChkCol)(.Value = "Closed late")) And (.Value = "Closed on time") Then
Cells(RowCnt, ChkCol).EntireRow.Hidden = True
Else
Cells(RowCnt, ChkCol).EntireRow.Hidden = False
End If
Next RowCnt
End Sub
问题是
If (Cells(RowCnt, ChkCol)(.Value = "Closed late")) And (.Value = "Closed on time") Then
没有有效的语法。应该是
If Cells(RowCnt, ChkCol).Value = "Closed late" And Cells(RowCnt, ChkCol).Value = "Closed on time") Then
不过,我建议作出以下改善:
使用Intersect(Target、Target.Parent.Range(单元格(BeginRow、ChkCol)、单元格(EndRow、ChkCol))
可以确保代码仅在第14列中更改的单元格上运行。这样就不会循环使用不必要的未更改单元格
另外,我建议激活选项显式
:在VBA编辑器中,转到工具›选项›
非常感谢你!工作完美。帮了大忙!
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim BeginRow As Long
BeginRow = 3
Dim ChkCol As Long
ChkCol = 14
Dim EndRow As Long
EndRow = 700 'could be replaced with dynamic solution below
'EndRow = Target.Parent.Cells(Target.Parent.Rows.Count, ChkCol).End(xlUp).Row
Dim ChangedCells As Range
Set ChangedCells = Intersect(Target, Target.Parent.Range(Cells(BeginRow, ChkCol), Cells(EndRow, ChkCol)))
If Not ChangedCells Is Nothing Then
Dim Cell As Range
For Each Cell In ChangedCells
If Cell.Value = "Closed late" Or _
Cell.Value = "Closed on time" Then
Cell.EntireRow.Hidden = True
End If
Next Cell
End If
End Sub