目录
1目标问题:
为什么VBA里,function可以运行的代码,在EXCEL用自定义函数,会返回错误值?
2 先说结论
2.1 最容易发生的原因
2.2 其他原因梳理
3 自定义函数返回值的情况
4 这3个自定义函数都会返回错误值,因为单元格的语法是VBA的,不符合EXCEL公式语法
5 可以正常运行,且返回值正确的 自定义函数
6 如果希望自定义函数能返回多个值呢?
7 那其他改动呢? 自定义函数能做的大概就是EXCEL的函数那些吧
例子1
Function testmd6(a, b)
testmd6 = a + b
End Function
Function testmd7(a, b) '起名问题
testmd7 = testmd6(a, b)
End Function
Function ty7(a, b)
ty7 = testmd6(a, b)
End Function
Function testmd8(a, b)
Call testmd6(a, b)
End Function
Public Function ff1(a As Integer, b As Integer) As Integer
ff1 = a + b
Cells(1, 1) = "abc"
End Function
Public Function ff2(a As Integer) As Integer
ff2 = a * 10
End Function
Public Function testff1(a As Integer, b As Integer) As Integer
testff1 = a + b
End Function
Public Function testff2(a As Integer) As Integer
testff2 = a * 10
End Function
Public Function Testthisout(number As Double) As Double
Testthisout = number * number
'Testthisout = result
End Function
Function fff3()
ff3 = 100
Debug.Print 100
End Function
Sub t2()
Debug.Print ff1(1, 2)
Debug.Print ff2(9)
Debug.Print Testthisout(3)
End Sub
Function testA1()
'如果没用返回值,就相当于testA1返回了空值 null none,EXCEL调用为自定义函数会返回0
'但是自定义函数要在EXCEL写法为 =testa1() 不能写成 =testa1否则会报错
End Function
Function testA2()
'如果没用返回值,就相当于testA2返回了空值 null none,EXCEL调用为自定义函数会返回0
b = 100
End Function
Function testA3()
'有返回值,EXCEL调用为自定义函数会testA3得返回值
testA3 = 100
End Function
自定义函数,不要用EXCEL保留词。比如 function sum111() ,这样VBA写对了函数,在EXCEL运行还是会报错!!!
'下面3个报错都因为,EXCEL里指定范围得写法和VBA不同
Function testB1()
Cells(3, 6) = "testB1"
End Function
Function testB2()
Range("f5") = "testB2"
End Function
Function testB3()
[f7] = "testB3"
End Function
'这个没问题,因为这里没涉及到excel里得操作
Function testB4()
Debug.Print "testB4"
End Function
'可以带参数,参数可以直接在EXCEL自定义函数时指定为其他单元格
Function testB5(a, b)
testB5 = (a + b)
End Function
Function testB6(a As Integer, b As Integer) As Integer
testB6 = (a + b)
End Function
Function testC1(a, b)
Dim c1()
ReDim c1(1 To 2)
c1(1) = a + b
c1(2) = a - b
testC1 = c1()
End Function