使用 Excel VBA 从公式返回 ABS 值
Posted
技术标签:
【中文标题】使用 Excel VBA 从公式返回 ABS 值【英文标题】:Return ABS value from formula using Excel VBA 【发布时间】:2017-06-26 03:07:32 【问题描述】:在下面给出的代码中,即orchestrated by Robin Mackenzie,我现在正试图从等式中获取绝对值。我尝试使用ABS()
命令:
.Formula = "=IF(ISNUMBER(" & strLowLimCol & "2)," & _
strMeasCol & "ABS(2-" & strLowLimCol & "2," & _
strMeasCol & "2))"
我认为我没有正确执行命令。你能帮我从方程中得到绝对值吗?
代码如下:
Option Explicit
Sub ReturnMarginal()
Dim ws As Worksheet
Dim lngLowLimCol As Long, strLowLimCol As String
Dim lngHiLimCol As Long, strHiLimCol As String
Dim lngMeasCol As Long, strMeasCol As String
Dim lngLastRow As Long
Dim wsf As WorksheetFunction
' get worksheetfunction references
Set wsf = Application.WorksheetFunction
' iterate worksheets
For Each ws In ThisWorkbook.Worksheets
' validate LowLimit label is on sheet
If ws.Rows(1).Find("LowLimit") Is Nothing Then Exit Sub
' get location of input data columns and number of rows
lngLowLimCol = wsf.Match("LowLimit", ws.Rows(1), 0)
lngHiLimCol = wsf.Match("HighLimit", ws.Rows(1), 0)
lngMeasCol = wsf.Match("MeasValue", ws.Rows(1), 0)
lngLastRow = ws.Cells(1, lngLowLimCol).End(xlDown).Row
' get column letters for input data columns
strLowLimCol = Split(ws.Cells(1, lngLowLimCol).Address(True, False), "$")(0)
strHiLimCol = Split(ws.Cells(1, lngHiLimCol).Address(True, False), "$")(0)
strMeasCol = Split(ws.Cells(1, lngMeasCol).Address(True, False), "$")(0)
' output headers
ws.Range("P1") = "Meas-LO"
ws.Range("Q1") = "Meas-Hi"
ws.Range("R1") = "Min Value"
ws.Range("S1") = "Marginal"
' assign formulas to outputs
' Meas-LO
With ws.Range("P2:P" & lngLastRow)
.Formula = "=IF(ISNUMBER(" & strLowLimCol & "2)," & _
strMeasCol & "2-" & strLowLimCol & "2," & _
strMeasCol & "2)"
End With
' Meas-Hi
With ws.Range("Q2:Q" & lngLastRow)
.Formula = "=" & strHiLimCol & "2-" & strMeasCol & "2"
End With
' Min Value
With ws.Range("R2:R" & lngLastRow)
.Formula = "=MIN(P2,Q2)"
End With
' Marginal
With ws.Range("S2:S" & lngLastRow)
.Formula = "=IF(AND(R2>=-3,R2<=3),""Marginal"",R2)"
End With
Next ws
End Sub
【问题讨论】:
这对 Excel 和 VBA 的使用仍然很糟糕 【参考方案1】:最简单的方法是在整个公式周围加上Abs
:
.Formula = "=ABS(IF(ISNUMBER(" & strLowLimCol & "2)," & _
strMeasCol & "2-" & strLowLimCol & "2," & _
strMeasCol & "2))"
但如果你愿意,你可以把它放在每个组件周围:
.Formula = "=IF(ISNUMBER(" & strLowLimCol & "2),ABS(" & _
strMeasCol & "2-" & strLowLimCol & "2),ABS(" & _
strMeasCol & "2))"
您必须记住的是 strMeasCol & "2-" & strLowLimCol & "2
正在使用两个地址创建一个公式,例如 G2-K2
- 所以您不能在其中启动 ABS
(即您将 @987654327 @ 在我的示例地址中的G
和2
之间,给出类似GABS(2-K2
)。
【讨论】:
以上是关于使用 Excel VBA 从公式返回 ABS 值的主要内容,如果未能解决你的问题,请参考以下文章