为什么我的用户定义函数不显示结果VBA



我创建了一个名为YRatio(Str)的UDF。当我在单元格中使用插入公式时,结果出现在对话框中,但在单元格中它显示"=YRatio(C2)">

我得到的结果是正确的。但它不会出现在细胞中。

Function YRatio(CellRef As String) As String
Dim Arr() As String
Dim tot As Integer
Dim yyes As Integer
Dim Str As String
Str = CellRef '.Value
Arr() = Split(Str, Chr(10))
For Each Line In Arr
tot = tot + 1
If Left(Line, 1) = "Y" Then
yyes = yyes + 1
End If
Next
YRatio = CStr(yyes) & "/" & CStr(tot)
End Function

在单元格内显示"=YRatio(C2)">

需要将单元格的格式更改为General。当前格式为Text

代码中的Arr() = Split(Str, Chr(10))也应该是Arr() = Split(Range(Str).Value, Chr(10))

Imp提示避免使用LINE和STR作为变量。使用更有意义的名字

你的代码可以写成
Option Explicit
Function YRatio(CellRef As Range) As String
Dim Arr() As String
Dim tot As Long
Dim yyes As Long
Dim itm As Variant

Arr() = Split(CellRef.Value2, Chr(10))

For Each itm In Arr
tot = tot + 1
If Left(itm, 1) = "Y" Then yyes = yyes + 1
Next
YRatio = yyes & "/" & tot
End Function

这里我将单元格作为Range传递。

现在你可以输入单元格=YRatio(C2),格式为General,它将工作。

你可以使用这个版本的代码,它使用UBound(Arr)来获取数组的总元素,而不是使用tot = tot + 1

Option Explicit
Function YRatio(CellRef As Range) As String
Dim Arr() As String
Dim yyes As Long
Dim itm As Variant

Arr() = Split(CellRef.Value2, Chr(10))

For Each itm In Arr
If Left(itm, 1) = "Y" Then yyes = yyes + 1
Next
YRatio = yyes & "/" & UBound(Arr)
End Function

最新更新