首页 > 解决方案 > 将百分比转换为数字,例如 20% 到 20

问题描述

我有一列包含百分比值。列单元格的格式是“数字”。 在此处输入图像描述

这是一个演示专栏。这些是用户输入的百分比值。

我试过的代码:

Sub Percent()
Dim cell As Variant
Dim cellValue As Variant
For Each cell In Selection
    With cell
        cellValue = .Text
        MsgBox cellValue
        If (cellValue Like "[0-9]*%") Then
            cellValue = Left(cellValue, Len(cellValue) - 1)
            .Value = cellValue
        Else
            Exit Sub
        End If
    End With
Next
End Sub

在运行它时,我想将“选定的单元格”转换为数字,即我想删除那个百分比符号,我不想要小数的值。只是整数(没有 % 符号)。

上面发布的代码有效,但该列应该是“文本”列。这意味着,在列的“格式单元格”选项中,它应该说文本而不是数字,然后只有我的代码有效。但是当我将“格式单元格”中的列更改为“数字”时,代码不起作用。

标签: vbaexcelwildcard

解决方案


你可以试试这个:

Sub Percent()
Dim cell As Variant
Dim cellValue As Variant
For Each cell In Selection
    With cell
         .NumberFormat = "0.00"
        .NumberFormat = "0"
        cellValue = .Value * 100
        .Value = cellValue
    End With
Next
End Sub

或这个 :

Sub Percent2()
Dim cell As Variant
Dim cellValue As Variant
For Each cell In Selection
    With cell
        cellValue = .Text
        MsgBox cellValue
        If (cellValue Like "[0-9]*%") Then
            Selection.NumberFormat = "0"
            cellValue = Left(cellValue, Len(cellValue) - 1)
            .Value = cellValue
        Else
            Exit Sub
        End If
    End With
Next
End Sub

推荐阅读