我有一个包含百分比值的列。列单元格的格式为" number"。
这是一个演示专栏。这些是用户输入的百分比值。
我尝试的代码:
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
在运行时,我想转换"选择的单元格"在数字,即我想删除该百分比符号,我不想要小数值。只是整数(没有%符号)。
上面发布的代码有效,但该列应该是" text"柱。这意味着,在"格式化单元格"列的选项,应该说文本不是数字,那么只有我的代码才有效。但当我更改"格式化单元格中的列时#34; as" number",代码不起作用。
答案 0 :(得分: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
答案 1 :(得分: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
我们:
答案 2 :(得分: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
答案 3 :(得分:0)
You can do this as follows:
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