微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VBA 如何创建此 If IsNumber 公式作为函数

如何解决VBA 如何创建此 If IsNumber 公式作为函数

所以我想转换这个公式 =IF(A3,IF(ISNUMBER(C3/B3),C3/B3,""),"") 变成一个私有函数,这样我就可以使用它了。我已经尝试过但未能让它在 VBA 中工作,如果它是数字并且是数字,我该如何从两个单元格中执行划分?

enter image description here

代码

Function GetSpendPerHead(Ra As Range,rb As Range,rc As Range) 
    GetSpendPerHead = "" 
    If Ra.Value = True Then
      If IsNumeric(rb.Value) And IsNumeric(rc.Value) Then 
        If rb.Value <> 0 Then
          GetSpendPerHead = rc / rb 
        End If  
      End If 
    End If 
End Function

解决方法

你的函数对我来说似乎很好用,这里有一些测试用例。

Sub UnitTestGetSpendPerHead()
    
    Dim ra As Range: Set ra = Range("A1")
    Dim rb As Range: Set rb = Range("B1")
    Dim rc As Range: Set rc = Range("C1")
    Dim test As Variant
    rb.NumberFormat = "General"
    
    ' Test 1
    ra.Value2 = ""
    rb.Value2 = 1
    rc.Value2 = 2
    test = GetSpendPerHead(ra,rb,rc)
    Debug.Print "Test 1 Result: " & test
    
    ' Test 2
    ra.Value2 = 2014
    rb.Value2 = 2
    rc.Value2 = "a"
    test = GetSpendPerHead(ra,rc)
    Debug.Print "Test 2 Result: " & test
    
    ' Test 3
    ra.Value2 = 2015
    rb.NumberFormat = "@"
    rb.Value2 = "4"
    rc.Value2 = 2
    test = GetSpendPerHead(ra,rc)
    Debug.Print "Test 3 Result: " & test
End Sub

Function GetSpendPerHead(ra As Range,rb As Range,rc As Range)
    GetSpendPerHead = ""
    If Not IsEmpty(ra.Value) Then
      If IsNumeric(rb.Value) And IsNumeric(rc.Value) Then
        If rb.Value <> 0 Then
          GetSpendPerHead = rc / rb
        End If
      End If
    End If
End Function
,
Function CheckNumber()

'Define the variables
Dim FirstNumber As Double
Dim SecondNumber As Double
Dim Result As Double

'If we have an error when are reading the variables go to Oops
On Error GoTo Oops
    'Read the first number from row 3 and column 3 (C)
    FirstNumber = Sheets("Sheet1").Cells(3,3).Value
    'Read the first number from row 3 and column 2 (B)
    SecondNumber = Sheets("Sheet1").Cells(3,2).Value
    'Calculate C3/B3
    Result = FirstNumber / SecondNumber
    'Get the result as message box
    MsgBox Result

'If we have error we get this message: Not Number
Oops:
    MsgBox "Not Number"

End Function
,

谢谢大家,调试后,问题改为或 Ra.Value = true ,然后我设置 Ra.Value = 1 并且它工作了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?