检查单元格是Excel VBA中的数字

Joe*_*Joe -2 excel vba excel-vba

在下面的代码中,我正在对单元格进行数值计算.但有时,其中一个单元格(例如"LosLimit")可能包含非数字值,如"---".如何检查单元格是否为数字.

如果是数字,则进行计算,否则从"MeasValue"返回值

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)
                .Range("P2:P" & lastRow).Formula = "=IF(ISNUMBER(" & .Cells(2, lowLimCol).Value2 & ")," & 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
Run Code Online (Sandbox Code Playgroud)

jam*_*art 5

你的答案就是问题所在!有一个函数isNumeric(variable_goes_here),它将返回true或false,例如

if isNumeric(x) then msgbox("Woop!")
Run Code Online (Sandbox Code Playgroud)

将返回一个true并给你消息框x = 45但是会跳过ifx = "Not a number"