将列的数据类型从Text更改为Number

时间:2017-10-11 16:18:50

标签: vba excel-vba excel

我需要将列的数据类型从Text更新为Number,以便我可以使用它来执行进一步的计算。以下代码对我不起作用。你能否建议解决这个问题?

Sub ConvertTextToNumber()

    Dim rRange As Range
    Dim rCell As Range
    Dim Rowcount As Long


    Worksheets("Input").Select
    Rowcount = Application.CountA(Range("C:C"))
    Set rRange = ActiveSheet.Range("AQ2:AQ" & Rowcount)

    For Each rCell In rRange.Cells

        rCell.Value = rCell.Value * 1

    Next rCell

End Sub

1 个答案:

答案 0 :(得分:1)

尝试在运行该循环之前将NumberFormat设置为数字格式。

Set rRange = ActiveSheet.Range("AQ2:AQ" & Rowcount)
rRange.NumberFormat = "#,##0" ' anything but "@" / text

For Each rCell In rRange.Cells
    Debug.Assert IsNumeric(rCell.Value) 'will break if not true
    rCell.Value = rCell.Value * 1
Next rCell

如果遇到错误,我添加Assert调用来中断执行;如果rRange包含任何单元格错误,rCell.Value * 1将引发类型不匹配运行时错误。

或者你可以跳过错误单元,如果错误单元应该是预期的那样:

For Each rCell In rRange.Cells
    If Not IsError(rCell.Value) Then
        rCell.Value = rCell.Value * 1
    End If
Next rCell