将excel单元格的格式从文本设置为带1位小数和“%”符号的数字

dldeef67  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(319)

下面是我的宏代码,转换文本为数字在以往任何一张Excel表格,并留下它与'%'符号连接:

'Convert text to numbers with one decimal place
            With rng
                .Value = .Value 'Convert text to numbers
                For Each cell In .Cells 'Loop through each cell in the range
                    If Right(cell.Value, 1) = "%" Then 'Check if the value ends with a percentage symbol
                        cell.Value = Left(cell.Value, Len(cell.Value) - 1) / 100 'Remove the percentage symbol and divide by 100
                        cell.NumberFormat = "0.0%" 'Set the number format to display one decimal place and a percentage symbol
                        cell.Value = cell.Value 'Remove trailing zero
                    End If
                Next cell
            End With

这段代码正确地将文本转换为数字,但是保留了2个小数位而不是1位。因此,对于值6.3%,它转换为6.30%。Numberformat不做任何事情。有没有帮助如何修复这个问题?

du7egjpx

du7egjpx1#

尝试在第7行添加\,使其看起来如下所示
cell.NumberFormat = "0.0\%" 'Set the number format to display one decimal place and a percentage symbol
通过在%符号前添加反斜杠\,可以转义该符号,并通知Excel将其视为文字字符,而不是数字格式代码的占位符。

oknwwptz

oknwwptz2#

实际上,将数字格式设置为“通用”,然后将文本转换为数字,在顶部将数字格式设置为0.0%固定了问题;em”

'Convert text to numbers with one decimal place
            With rng
                .NumberFormat = "General"
                .Value = .Value 'Convert text to numbers
                .NumberFormat = "0.0%"
            End With

相关问题