【发布时间】:2017-11-28 12:18:06
【问题描述】:
这个问题是从solution found here 构建的。我希望能够检查“LowLimit”单元格是否是数字。如果是则执行方程,否则从“MeasValue”列返回值。这是我当前结果的数据集示例:
如您所见,第 6 次数据输入计算给出了错误的计算。公式中的数字 LowLimit 值 22 似乎是硬编码的。你能帮我解决这个问题吗?谢谢。
这是我目前的代码:
Sub ReturnMarginal()
'UpdatebySUPERtoolsforExcel2016
Dim xOut As Worksheet
Dim xWb As Workbook
Dim xWks As Worksheet
Dim InterSectRange As Range
Dim lowLimCol As Integer
Dim hiLimCol As Integer
Dim measCol As Integer
Application.ScreenUpdating = False
Set xWb = ActiveWorkbook
For Each xWks In xWb.Sheets
xRow = 1
With xWks
FindString = "LowLimit"
If Not xWks.Rows(1).Find(FindString) Is Nothing Then
.Cells(xRow, 16) = "Meas-LO"
.Cells(xRow, 17) = "Meas-Hi"
.Cells(xRow, 18) = "Min Value"
.Cells(xRow, 19) = "Marginal"
lastRow = .UsedRange.Rows.Count
lowLimCol = Application.WorksheetFunction.Match("LowLimit", xWks.Range("1:1"), 0)
hiLimCol = Application.WorksheetFunction.Match("HighLimit", xWks.Range("1:1"), 0)
measLimCol = Application.WorksheetFunction.Match("MeasValue", xWks.Range("1:1"), 0)
'If IsNumeric(.Cells(2, lowLimCol).Value2) Then
' .Range("P2:P" & LastRow).Formula = "=" & Cells(2, measLimCol).Address(False, False) & "-" & Cells(2, lowLimCol).Address(False, False)
'Else
' .Range("P2:P" & LastRow).Formula = "=" & Cells(2, measLimCol).Address(False, False)
'End If
.Range("P2:P" & lastRow).Formula = "=IF(ISNUMBER(" & .Cells(2, lowLimCol).Value & ")," & Cells(2, measLimCol).Address(False, False) & "-" & Cells(2, lowLimCol).Address(False, False) & "," & Cells(2, measLimCol).Address(False, False) & ")"
.Range("Q2:Q" & lastRow).Formula = "=" & Cells(2, hiLimCol).Address(False, False) & "-" & Cells(2, measLimCol).Address(False, False)
.Range("R2").Formula = "=min(P2,Q2)"
.Range("R2").AutoFill Destination:=.Range("R2:R" & lastRow)
.Range("S2").Formula = "=IF(AND(R2>=-3, R2<=3), ""Marginal"", R2)"
.Range("S2").AutoFill Destination:=.Range("S2:S" & lastRow)
End If
End With
Application.ScreenUpdating = True 'turn it back on
Next xWks
End Sub
【问题讨论】:
-
你为什么要使用 VBA?
-
为避免硬编码值,您可以尝试使用
.Address而不是.Value。 -
让我明确一点:您应该不为此使用 VBA。
-
@AndreTerra - 猜测 OP 正在使用 VBA,因为显示的代码暗示
LowLimit、HighLimit和MeasValue不会总是出现在H、I和J列中。 -
@RobinMackenzie 他可以为此使用命名范围
标签: vba excel excel-formula