在Excel中将文本格式快速转换为数字格式-VBA

时间:2018-10-05 10:22:55

标签: excel vba excel-vba

我正在寻找一个代码,该代码将转换大量带有数字的单元格的单元格格式。我应用的过程是将数字“ 1”写入一个空单元格,将其复制,然后将整个选择乘以数字作为文本存储。与提供Excel的自动“转换为数字”建议相比,这确实非常快(建议使用年龄超过1000个单元格)。 我写了这个宏(它可以工作,但不如上述过程那么快):

Option Explicit

Sub nasobeni()

Dim cell As Range
Dim one As Integer

one = 1

For Each cell In Selection
    cell.value = cell.value * one
Next

Application.CutCopyMode = False
Selection.NumberFormat = "0"

End Sub

有人建议,这会加快这一过程吗? 谢谢

2 个答案:

答案 0 :(得分:1)

确保常规单元格编号格式,然后是“文本到列”,“固定宽度”,“完成”。

with selection.columns(1)
    .numberformat = "General"
    .TextToColumns Destination:=.cells(1), DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
end with

文本到列一次只能处理一个列,但是循环浏览列是一件小事。

dim i as long

with selection
    .numberformat = "General"
    for i=1 to .columns.count
        .columns(i).TextToColumns Destination:=.columns(i).cells(1), DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
    end with
end with

答案 1 :(得分:1)

设置范围并更改格式后,只需将值写回范围即可。


Option Explicit
Sub colaTextToNumbers()
    Dim R As Range

'Can be set in many different ways
Set R = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp)) 'for column A

'Set R = Selection
'Set R = whatever

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
End With

With R
    .EntireColumn.NumberFormat = "General" 'or could limit this just to R, not entire column
    .Value = .Value
End With

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = xlCalculationAutomatic
End With

End Sub