假设我在excel中有一个列作为年龄
年龄
43个
54个
62个
71个
我想将其重命名为
年龄
41-50
51-60
61-70
71-80
我该怎么做?
由于
答案 0 :(得分:0)
使用以下数据:
运行此宏:
Sub luxation()
Dim i As Long, r As Range, v As Variant
With Application.WorksheetFunction
For i = 2 To 5
Set r = Cells(i, "A")
v = r.Value
r.Value = .Round(v, -1) & "-" & .RoundUp(v, -1)
Next i
End With
End Sub
将产生:
您可以更改循环中的限制以覆盖所有数据。
答案 1 :(得分:0)
在处理更改范围时,我建议使用以下内容:
Sub test()
Dim a As Variant, b As Long
For Each a In Selection.Cells
If IsNumeric(a.Value) And Len(a.Value) Then
b = Int(a.Value / 10) * 10
a.Value = b + 1 & 0 - b - 10
End If
Next
End Sub
如果您选择整个列C,这也有效。但它会以您请求的格式更改所选范围内的所有数字(空单元格保持为空但0将变为“1-10”)
然而:对更大的范围执行此操作可能会冻结excel一点(仅计算时间)。在这种情况下,您可能希望使用更快的代码:
Sub test2()
Dim b As Long, i As Long, j As Long, vars As Variant
vars = Intersect(Selection, Selection.Parent.UsedRange).Value
For i = 1 To UBound(vars)
For j = 1 To UBound(vars, 2)
If IsNumeric(vars(i, j)) And Len(vars(i, j)) Then
b = Int(vars(i, j) / 10) * 10
vars(i, j) = b + 1 & 0 - b - 10
End If
Next
Next
Intersect(Selection, Selection.Parent.UsedRange).Value = vars
End Sub
如果你有一个设定范围,其中数字总是(并且不想选择)你也可以用这样的代码预选它:
Sub test3()
Dim b As Long, i As Long, j As Long, vars As Variant, rng As Range
Set rng = Sheets("Sheet1").Range("C2:C20000")
vars = Intersect(rng, rng.Parent.UsedRange).Value
For i = 1 To UBound(vars)
For j = 1 To UBound(vars, 2)
If IsNumeric(vars(i, j)) And Len(vars(i, j)) Then
b = Int(vars(i, j) / 10) * 10
vars(i, j) = b + 1 & 0 - b - 10
End If
Next
Next
Intersect(rng, rng.Parent.UsedRange).Value = vars
End Sub
如果您还有任何疑问,请写下评论;)