类似这样的:
Sub OutputEnergy()
'y = Columns to check: 2-25
'x = Rows to check: 2-152
'z = check the next 4 cells
Dim x, y, z, check
'Clear the range where we store the #N/A or Energy Outputs
Range("B153:Y153") = vbNullString
For y = 2 To 25
For x = 2 To 152
If Cells(x, y) > Range("Z2") Then 'If value is greater than Z2
check = True 'Let's check the next 4
For z = 1 To 4 'If any of them fail
If Cells(x + z, y) < Range("Z2") Then
check = False 'The check fails
Exit For
End If
Next z
If check = True Then 'If the check doesn't fail
Cells(153, y) = Cells(x, 1) 'Set cell 153 to the energy level
Exit For
End If
End If
Next x 'If no energy level was set - #N/A
If Cells(153, y) = vbNullString Then Cells(153, y) = "#N/A"
Next y
End Sub
编辑:作为函数:
函数用法:
=OutputEnergy(Range, Threshold, [Number of cells to check], [Using Headers?])
基本上,给它检查的范围,给它一个阈值。
之后要检查的单元格数默认为 4 个。
要获得“能量”,它会获得行号(如果使用标题,则减去 1)
Function OutputEnergy(TheRange As Range, Threshold As Variant, Optional NextCells As Integer = 4, Optional OffsetForHeader As Boolean = True) As Variant
Dim c, x, check
For Each c In TheRange
If c.Value > Threshold Then
check = True
For x = 1 To NextCells
If c.Offset(x, 0) < Threshold Then
check = False
Exit For
End If
Next x
If check = True Then
OutputEnergy = IIf(OffsetForHeader, c.Row - 1, c.Row)
Exit Function
End If
End If
Next c
OutputEnergy = CVErr(xlErrNA)
End Function
再次编辑 - 输出到所有工作表:
OutputEnergyToSheet 接受工作表作为参数:
Sub OutputEnergyToSheet(TheSheet As String)
'y = Columns to check: 2-25
'x = Rows to check: 2-152
'z = check the next 4 cells
Dim x, y, z, check
'Clear the range where we store the #N/A or Energy Outputs
With Sheets(TheSheet)
.Range("B153:Y153") = vbNullString
For y = 2 To 25
For x = 2 To 152
If .Cells(x, y) > .Range("Z2") Then 'If value is greater than Z2
check = True 'Let's check the next 4
For z = 1 To 5 'If any of them fail
If .Cells(x + z, y) < .Range("Z2") Then
check = False 'The check fails
Exit For
End If
Next z
If check = True Then 'If the check doesn't fail
.Cells(153, y) = Int(.Cells(x, 1)) 'Set cell 153 to the energy level
Exit For
End If
End If
Next x 'If no energy level was set - #N/A
If .Cells(153, y) = vbNullString Then .Cells(153, y) = "#N/A"
Next y
End With
End Sub
OutputEnergyToAllSheets 循环遍历每个工作表并调用新的 sub:
Sub OutputEnergyToAllSheets()
Dim w
For Each w In ThisWorkbook.Worksheets
If Not InStr(w.Name, "Total") > 0 And Not InStr(w.Name, "eV") > 0 Then
OutputEnergyToSheet w.Name
End If
Next w
End Sub