【问题标题】:How to keep variable amount of numbers after decimals如何在小数点后保留可变数量的数字
【发布时间】:2015-05-08 05:07:15
【问题描述】:

我正在使用 Excel 2007。我有多个数据集,每行中的字符数是随机的。例如:

A1 1.60 

A2 0.008 

A3 0.900 

A4 1.0 

A5 0.56 

A6 1.703

我需要在不同的页面上把它变成不同的顺序,比如

A1 1.60

A2 0.900

A3 1.0

A4 0.56

A5 1.703

A6 0.008

不幸的是,每当我将它移动到新页面(例如,我可以使用 =Page1!A1 移动它)时,数字都会恢复到

A1 1.6

A2 0.9

A3 1

A4 0.56

A5 1.703

A6 0.008

所以我失去了零。

更复杂的是,每个条目/行/列的字符数因数据集而异。这意味着使用=TEXT(A1,"#.#0") 不能 工作——有时我的 A1 可能是 1498 或其他。

我(可能)正在寻找能够“计算”显示的小数位数并自动生成的代码。或者任何其他方法可以让我的变量数据正确的小数位数(或缺少小数位数)。 VBA/宏/函数?

【问题讨论】:

    标签: function excel decimal excel-2007 vba


    【解决方案1】:

    我认为您可以根据您的情况调整此代码...

    Public Sub MaintainTrailingZeroFormat()
    Dim s As String
    Dim lngLength As Long, lngDecimal As Long, lngTrailingZero As Long
    Dim r As Range
    ''Grab cell value as text
    s = ActiveWorkbook.ActiveSheet.Range("A2").Text
    ''Find decimal from beginning of string
    lngDecimal = InStr(s, ".")
    ''Find total length of string
    lngLength = Len(s)
    ''Subtract to find number of trailing zeros
    lngTrailingZero = i - st
    ''Set destination cell format to 'TEXT'
    ActiveWorkbook.Sheets(2).Range("A1").NumberFormat = "@"
    ''Populate cell with text value
    ActiveWorkbook.Sheets(2).Range("A1") = FormatNumber(s, EX)
    
    End Sub
    

    【讨论】:

    • 我不熟悉代码最后一行的FormatNumber,Marshall。那是自定义 VBA 函数吗?
    • 不,它不是自定义的......它在对象浏览器中作为 VBA 函数。
    猜你喜欢
    • 2022-12-07
    • 2022-10-12
    • 1970-01-01
    • 2021-06-05
    • 2018-02-09
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多