将百分比转换为数字,例如20%到20

问题描述 投票:0回答:4

我有一个包含百分比值的列。列单元格的格式为“数字”。 enter image description here

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

我试过的代码:

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

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

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

excel vba excel-vba wildcard
4个回答
0
投票

你可以这样做:

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
                .NumberFormat = "General"    <-- convert the format into number
                .Value = .Value * 100        <--
            Else
                Exit Sub
            End If
        End With
    Next

End Sub

1
投票

你可以试试这个:

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

0
投票

如果你想要数字作为文本:

Sub Percent()
    Dim cell As Variant
    Dim cellValue As Variant
    For Each cell In Selection
        With cell
            cellValue = .Text
            If Right(cellValue, 1) = "%" Then
                cellValue = "'" & Left(cellValue, Len(cellValue) - 1)
                .Value = cellValue
            Else

            End If
        End With
    Next
End Sub

我们:

  • 修改了%test
  • 插入前缀字符
  • 允许循环继续

0
投票

我会先将单元格转换为数字,再乘以100,然后转换为文本。

Sub Percent()

    Dim Cel As Range

    For Each Cel In Selection.Cells
        With Cel
            .NumberFormat = "0.00"
            .Value2 = Round(.Value2 * 100, 0)
            .NumberFormat = "@"
        End With
    Next Cel

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.