范围格式中每个单元格的 VBA 作为百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42844778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:47:11  来源:igfitidea点击:

VBA For Each cell In Range Format as Percentage

vbaexcel-vbaloopsnumber-formattingpercentage

提问by anonymous

I've looked around for this and it seems so simple, yet I can't get it to work.

我环顾四周,它看起来很简单,但我无法让它工作。

I have a table and one column needs to be formatted as a percentage. Below is my code but it is not formatting the cells, it just leaves them as the decimal.

我有一张表格,其中一列需要格式化为百分比。下面是我的代码,但它没有格式化单元格,它只是将它们保留为小数。

I think this is because cell, even though declared as a range, is actually the value of the cell so I don't know how to refer to that range.

我认为这是因为cell即使声明为范围,实际上也是单元格的值,所以我不知道如何引用该范围。

My returnRebatevariable is declared as a range and the loop is looping through the correct range.

我的returnRebate变量被声明为一个范围,并且循环在正确的范围内循环。

Code:

代码:

Dim cell As Range, p As Double
For Each cell In returnRebate
    p = cell.Value

    If p <> 0 And p > 1 Then
        p = p * 0.01
        cell.Value = p
        cell.NumberFormat = "Percent"    'Not formatting here
     ElseIf p < 1 And p > 0 Then
        'do nothing to it
    Else
        cell.Value = vbNullString
    End If
Next

回答by RyanL

Try replacing .NumberFormat='Percent'with .NumberFormat="0.00%"

尝试替换.NumberFormat='Percent'.NumberFormat="0.00%"