检查单元格是否在范围内,如果是,则在Excel VBA中返回单词“Marginal”

我试图检查Excel电子表格N列中的值是否在-10到10的范围内。如果是,则在O列中返回单词“Marginal”,否则返回N中的值。我不是当然如何去做这件事。 这是我到目前为止的代码:

Sub SearchFolders() 'UpdatebySUPERtoolsforExcel2016 Dim xOut As Worksheet Dim xWb As Workbook Dim xWks As Worksheet Dim InterSectRange As Range Application.ScreenUpdating = False Set xWb = ActiveWorkbook For Each xWks In xWb.Sheets xRow = 1 With xWks .Activate 'Activating the worksheet .Cells(xRow, 12) = "Meas-LO" .Cells(xRow, 13) = "Meas-Hi" .Cells(xRow, 14) = "Min Value" .Cells(xRow, 15) = "Marginal" LastRow = ActiveSheet.UsedRange.Rows.Count Range("L2").Formula = "=G2+I2" Range("L2").AutoFill Destination:=Range("L2:L" & LastRow) Range("M2").Formula = "=I2-F2" Range("M2").AutoFill Destination:=Range("M2:M" & LastRow) Range("N2").Formula = "=min(L2,I2)" 'Set InterSectRange = Application.Intersect(rng1, rng2) 'If Range("N2").AutoFill Destination:=Range("N2:N" & LastRow) End With Application.ScreenUpdating = True 'turn it back on Next xWks End Sub 

 For Each xWks In xWb.Sheets xRow = 1 With xWks '.Activate '<< not required, and best avoided .Cells(xRow, 12) = "Meas-LO" .Cells(xRow, 13) = "Meas-Hi" .Cells(xRow, 14) = "Min Value" .Cells(xRow, 15) = "Marginal" LastRow = .UsedRange.Rows.Count .Range("L2").Formula = "=G2+I2" .Range("L2").AutoFill Destination:=.Range("L2:L" & LastRow) .Range("M2").Formula = "=I2-F2" .Range("M2").AutoFill Destination:=.Range("M2:M" & LastRow) .Range("N2").Formula = "=min(L2,I2)" .Range("N2").AutoFill Destination:=.Range("N2:N" & LastRow) .Range("O2").Formula = "=IF(AND(N2>=-10, N2<=10), ""Marginal"", N2)" .Range("O2").AutoFill Destination:=.Range("O2:O" & LastRow) End With Application.ScreenUpdating = True 'turn it back on Next xWks 
  1. 您正在使用With … End With块,但忽略Range调用。
  2. 您可以将公式放入所有单元格中。 无需将公式放入顶部单元格并填充。

     With xWks .Cells(xRow, 12).resize(1, 4) = array("Meas-LO", "Meas-Hi", "Min Value", "Marginal") LastRow = application.max(.cells(.rows.count, "F").end(xlup).row, _ .cells(.rows.count, "G").end(xlup).row, _ .cells(.rows.count, "I").end(xlup).row, _ .cells(.rows.count, "L").end(xlup).row) .Range("L2:L" & LastRow).Formula = "=G2+I2" .Range("M2:M" & LastRow").Formula = "=I2-F2" .Range("N2:N" & LastRow).Formula = "=min(L2,I2)" End With 
 Sub SearchFolders() Dim ws As Worksheet, h As Variant, f As Variant, cols As Long h = Array("Meas-LO", "Meas-Hi", "Min Value", "Marginal") f = Array("=G2+I2", "=I2-F2", "=Min(L2,I2)", "=IF(AND(N2>=-10, N2<=10),""Marginal"",N2)") cols = UBound(h) + 1 For Each ws In ThisWorkbook.Worksheets ws.Cells(1, "L").Resize(1, cols).Value2 = h ws.Cells(1, "L").Offset(1).Resize(ws.UsedRange.Rows.Count - 1, cols).Formula = f Next End Sub