您好,我在VBA上很新,因为我在这里遇到问题,如果条件正确,则在筛选的单元格中输入“是”,否则输入“否”
但是当我为LOOP运行代码时,即使条件不成立,它也会将yes数据全部放入
VBA
Sub check()
Dim j As Long
Dim dsheet As Worksheet
Dim lastrow As Long
Dim fr As Range
Dim psheet As Worksheet
Dim c As Range
Set dsheet = Worksheets("Workings")
Set psheet = Worksheets("sheet1")
lastrow = dsheet.Cells(Rows.Count, 1).End(xlUp).row
For j = 1 To lastrow
psheet.Range("M2").Value = dsheet.Range("A2" & j)
psheet.Range("N2").Value = dsheet.Range("B2" & j)
psheet.Range("A1").AutoFilter Field:=1, Criteria1:=psheet.Range("M2")
psheet.Range("B1").AutoFilter Field:=2, Criteria1:=psheet.Range("N2")
psheet.Range("A2:I" & psheet.Cells(Rows.Count, 1).End(xlUp).row).SpecialCells (xlCellTypeVisible)
dsheet.Range("M2").Value = dsheet.Range("A" & j)
dsheet.Range("N2").Value = dsheet.Range("B" & j)
dsheet.Range("A1").AutoFilter Field:=1, Criteria1:=dsheet.Range("M2")
dsheet.Range("B1").AutoFilter Field:=2, Criteria1:=dsheet.Range("N2")
Set fr = psheet.Range("C2:C50").Find(what:="12345", MatchCase:=True)
For Each c In dsheet.Range("E2:E2000" & Range("A" & Rows.Count).End(xlUp).row).SpecialCells(xlCellTypeVisible)
If fr Is Nothing Then
dsheet.Range("A2" & Range("A" & Rows.Count).End(xlUp).row).SpecialCells (xlCellTypeVisible)
If c.Offset(, -1).Value = vbNullString Then Exit For
c.Value = "NO"
Else
dsheet.Range("A2" & Range("A" Rows.Count).End(xlUp).row).SpecialCells (xlCellTypeVisible)
If c.Offset(, -1). Value =vbNullString Then Exit For
c.Value = "Yes"
End If
Next c
Next j
dsheet. AutoFilterMode = False
psheet. AutoFilterMode = False
End Sub
所以,我希望代码根据条件输入“是”或“否”,如果有人在此问题上为我提供帮助,将会很有帮助
答案 0 :(得分:0)
每个If语句都需要一个End If。应该是这样的:此外,适当的缩进有助于使代码更具可读性。
If fr Is Nothing Then
dsheet.Range("A2" & Range("A" & Rows.Count).End(xlUp).row).SpecialCells (xlCellTypeVisible)
If c.Offset(, -1).Value = vbNullString Then Exit For
End If
c.Value = "NO"
Else
dsheet.Range("A2" & Range("A" Rows.Count).End(xlUp).row).SpecialCells
(xlCellTypeVisible)
If c.Offset(, -1). Value =vbNullString Then Exit For
End If
c.Value = "Yes"
End If