如何将Excel中的文本转换为数字?

时间:2012-12-31 10:08:10

标签: excel-vba vbscript vba excel

我刚刚运行了一个宏并得到了以下内容:

Sub Macro1()
'
' Macro1 Macro
'

'
    Columns("B:B").Select
    Range("B4").Activate
    Selection.NumberFormat = "0.00"
    Selection.NumberFormat = "@"
End Sub

现在无法理解Selection.NumberFormat = "0.00"Selection.NumberFormat = "@"之间的区别你能帮我理解一下吗?

我还试图将一些数字作为Excel中的文本转换为数字。这样做会有什么好的语法?

快照:

Existing Number format

修改

我尝试将存储为text的所有数字转换为下面的数字,但没有任何改变。如果我错了,请指导:

objSheet1.Columns(11).NumberFormat = "0"

2 个答案:

答案 0 :(得分:3)

这是你在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long, i As Long

    '~~> Change this to the relevant sheet name
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Col B
        .Columns(2).NumberFormat = "0.00"

        '~~> Get the last row
        lRow = .Range("B" & .Rows.Count).End(xlUp).Row

        For i = 1 To lRow
            .Range("B" & i).Formula = .Range("B" & i).Value
        Next i
    End With
End Sub

<强> SCREENSHOT

enter image description here

答案 1 :(得分:0)

要将存储为单元格中的数字的文本转换为数字,您可以尝试以下方法:

Sub ConvertTextInCellToNumber(ByVal cellLocation As String)

Dim txt As String
txt = range(cellLocation).text

On Error GoTo Catch

Dim txtAsNumber As Double
txtAsNumber = txt

range(cellLocation).Value = txtAsNumber

Catch:

End Sub
相关问题