Excel 显示1/8英寸的VBA用户定义函数显示为空白

Excel 显示1/8英寸的VBA用户定义函数显示为空白,excel,vba,format,rounding,user-defined-functions,Excel,Vba,Format,Rounding,User Defined Functions,我对VBA很陌生。我写了这个UDF(我第一次正确的编码),我把事情搞砸了,但我不知道是什么。我知道的很少,目前正在学习一门课程,但在我未受过教育的眼中,大多数答案似乎是可以互换的 此外,如果有人对减少变量数量或清理代码有任何建议,我将不胜感激 Function NearestEighth(number) As String Dim NE As String WholeNum = Application.WorksheetFunction.RoundDown(number, 0) DecNum

我对VBA很陌生。我写了这个UDF(我第一次正确的编码),我把事情搞砸了,但我不知道是什么。我知道的很少,目前正在学习一门课程,但在我未受过教育的眼中,大多数答案似乎是可以互换的

此外,如果有人对减少变量数量或清理代码有任何建议,我将不胜感激

Function NearestEighth(number) As String
Dim NE As String

WholeNum = Application.WorksheetFunction.RoundDown(number, 0)
DecNum = (number) - (WholeNum)

    Near = Round(DecNum * 8, 0) / 8

Select Case Near

Case Is = 0
NE = ""

Case Is = 0.125
NE = "1/8"

Case Is = 0.25
NE = "1/4"

Case Is = 0.375
NE = "3/8"

Case Is = 0.5
NE = "1/2"

Case Is = 0.625
NE = "5/8"

Case Is = 0.75
NE = "3/4"

Case Is = 0.875
NE = "7/8"

End Select

Prelim = (number)

Select Case Prelim
    
    Case Prelim > 0 And Prelim < 1
    FractionFormat = NE
    
    Case Prelim > 1
    FractionFormat = (WholeNum) & "-" & (NE)
    
End Select

NearestEighth = FractionFormat

End Function
作为字符串的近右(数字)函数
像线一样变暗
WholeNum=Application.WorksheetFunction.RoundDown(数字,0)
DecNum=(数字)-(全数)
近=圆形(DecNum*8,0)/8
选择Case Near
大小写为=0
NE=“”
案例Is=0.125
NE=“1/8”
案例Is=0.25
NE=“1/4”
案例Is=0.375
NE=“3/8”
案例Is=0.5
NE=“1/2”
案例Is=0.625
NE=“5/8”
案例Is=0.75
NE=“3/4”
案例Is=0.875
NE=“7/8”
结束选择
Prelim=(数字)
选择Case Prelim
案例Prelim>0和Prelim<1
FractionFormat=NE
案例预检>1
FractionFormat=(整体)和“-”和(东北)
结束选择
Nearestighth=分形格式
端函数
考虑:

Public Function NearestEighth(number As Double) As String
    Dim wf As WorksheetFunction, n8 As Double
    Set wf = Application.WorksheetFunction
    
    n8 = wf.Round(number * 8, 0) / 8
    
    NearestEighth = wf.Text(n8, "# -?/8")
End Function

选择..大小写
只能用于不同的大小写,不能用于连续范围

使用
If
替换
Select Case Prelim。。结束选择

If Prelim > 0 And Prelim < 1 Then
    FractionFormat = NE
ElseIf Prelim > 1 Then 
    FractionFormat = (WholeNum) & "-" & (NE)
End If
如果Prelim>0且Prelim<1,则
FractionFormat=NE
ElseIf Prelim>1则
FractionFormat=(整体)和“-”和(东北)
如果结束

使用溢出范围(MS365)写入整个数据集。

使用MS 365,您甚至可以调用一个过程,使用所谓的溢出范围(例如
“B1#”
)来引用动态目标,一次写入所有值:

Option Explicit

Sub ShowNearestEighths()
With Sheet1                  ' referencing the project's worksheet by Code(Name)
    Dim lastRow As Long
    lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    'calculate nearest eighths
    .Range("B1").Formula2 = "=Round(A1:A" & lastRow & " * 8, 0) / 8"
    'use spill range to format
    .Range("B1#").NumberFormat = "# -?/8"
End With
End Sub


请注意,
Round
使用银行取整,您可能希望使用
工作表函数.Round
。为什么不使用格式
#?/8
?如果要将文本作为输出:
=text(A1,“#?/8”)
不需要vba。它不供我使用。我已经在Excel中完成了这项工作,但我希望能够简单地调用该函数。而且,对于像我这样的新手来说,这似乎是一个足够简单的任务和很好的实践。如果你需要自定义项:
nearestighth=Format(number,“\35; \-?/?”
@ScottCraner,我试过了。它给了我一些奇怪的结果。0.3得率-?/?,0.7得率为1-?/?。我觉得这太离谱了。我尝试单独添加计算,但得到了类似的结果<代码>函数Craner2(数字)近暗双近=圆形(数字*8,0)/8 Craner2=格式(数字“\-?/?”)结束函数