这是一个演示专栏。这些是用户输入的百分比值。
我试过的代码:
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
在运行它时,我想转换数字中的“选定单元格”,即我想删除该百分比符号,我不希望小数值。只是整数(没有%符号)。
上面发布的代码有效,但该列应该是“文本”列。这意味着,在列的“格式单元格”选项中,应该说文本不是数字,那么只有我的代码可以工作。但是当我将“格式单元格”中的列更改为“数字”时,代码不起作用。
你可以这样做:
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
你可以试试这个:
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
如果你想要数字作为文本:
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
我们:
我会先将单元格转换为数字,再乘以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