循环在VBA中获得结果

图片

码:

Private Sub CommandButton1_Click() Dim ws As Worksheet Dim lastRow As Long Application.ScreenUpdating = False Set ws = ThisWorkbook.Sheets("Sheet1") With ws lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row .Range("P2").Formula = "=IF(MOD(SUMPRODUCT(($B$2:$B2=B2)*($K$2:$K2=K2)),3)=1,1,0)" .Range("P2").AutoFill Destination:=.Range("P2:P" & lastRow) .Range("P2:P" & lastRow).Value = .Range("P2:P" & lastRow).Value .Range("F2").Formula = "=IF" End With Application.ScreenUpdating = True End Sub 

我想要实现的是使用现有的代码继续添加以获得F列中的值来获取数量。

如果数量<36,则在“点”栏中有1个点;
如果数量为36-45,则在“点”栏中为2点;
如果数量多于46,则在“点”栏中有3个点。

试试这个公式


 Option Explicit Private Sub CommandButton1_Click() Dim ws As Worksheet, lr As Long Application.ScreenUpdating = False Set ws = ThisWorkbook.Sheets("Sheet1") lr = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row With ws.Range("P2:P" & lr) .Formula = "=IF(COUNTIF(B$2:B2,B2)>1, 0, IF(F2<36, 1, IF(F2<46, 2, 3)))" .Value = .Value End With Application.ScreenUpdating = True End Sub 

只需在代码End with之前添加下面的行即可

 .Range("Q2").Formula = "=IF(AND(F2<36,F2>0),1,IF(AND(F2>=36,F2<=45),2,IF(F2>46,3,""Zero or Beyong 46"")))" .Range("Q2").AutoFill Destination:=.Range("Q2:Q" & lastRow) .Range("Q2:Q" & lastRow).Value = .Range("Q2:Q" & lastRow).Value