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

标签 excel vba format rounding user-defined-functions

我对 VBA 很陌生。我写了这个 UDF(我的第一个正确的编码),但我搞砸了一些东西,但我不知道是什么。我知之甚少,目前正在学习一门类(class),但在我没有受过教育的眼中,大多数答案似乎都是可以互换的。

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

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

最佳答案

考虑:

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

enter image description here

关于excel - 显示 1/8 英寸的 VBA 用户定义函数显示空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64140353/

相关文章:

vba - 使用vba代码过滤掉数据透视表中的零

excel - 将命名范围设置为整数

c# - 在 C# 中获取 NamedRange 控件的句柄

excel - VBA网页抓取问题

html - 如何将 Nav、Title 和 Image 放在一行?

excel - 使用 "FIND"公式查找与给定字符不同的大小写

excel - 在 VBA Excel 上遇到 XML 阶段问题

regex - 如何使用正则表达式提取具有特定单位的值并求和

if-statement - SSRS 报告数字格式

date - Elastic(搜索):查询结果日期格式与存储格式不同