在下面的代码中,如果特定单元格中的数字是数字,我试图进行计算,否则返回其他单元格中的数字。我认为我的实现是不正确的,因为如果第一个单元格不是数字,我只会填充其他状态,反之亦然。你能告诉我怎么解决这个问题吗?
这是数据的一个例子:
第6个条目应在Meas-LO栏中返回27。
由于
这是代码
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).Address(False, False)) 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("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
答案 0 :(得分:2)
Cells(2, lowLimCol).Address(False, False)
返回字符串地址而不是值。所以它永远不会是数字。
更改为:
.Cells(2, lowLimCol).Value2
答案 1 :(得分:1)
在了解了您对问题第二部分的意义之后,我认为对您的公式设置方式的最快解决方法是使用公式填充整个列。
这比循环遍历代码中的每个单元格更快,以检查它是否为数字。您可以使用一个公式来填充整个范围,该公式可以检查电子表格本身:例如=IF(ISNUMBER(C1),C1-D1,C1)
要在代码中获取,我会替换整个if isNumeric then...
替换此部分:
If IsNumeric(Cells(2, lowLimCol).Address(False, False)) 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, measLimCol).Value2 & ")," & Cells(2, measLimCol).Address(False, False) & "-" & Cells(2, lowLimCol).Address(False, False) & "," & Cells(2, measLimCol).Address(False, False) & ")"