VBA to convert texts to numbers except formula and non-numeric texts

百般思念 提交于 2019-12-11 03:35:18

问题


I have a Range("B6:T10000")

Data in the range are a mixture of blanks,#'s ,numbers (formatted as texts), texts and most importantly formulas.

Can someone please help with a VBA macro to:

  • Find anything that looks like number and convert it to number
  • Ignore the rest
  • Don't convert formulas to values

Thank you very much


回答1:


Give this a try:

Sub Converter()
    Dim rBig As Range, r As Range, v As Variant
    Set rBig = Range("B6:T10000")
    For Each r In rBig
        v = r.Value
        If v <> "" And r.HasFormula = False Then
            If IsNumeric(v) Then
                r.Clear
                r.Value = v
            End If
        End If
    Next r
End Sub

EDIT#1:

This version ignores errors:

Sub Converter()
    Dim rBig As Range, r As Range, v As Variant
    Set rBig = Range("B6:T10000")
    For Each r In rBig
        v = r.Value
        If Not IsError(v) Then
            If v <> "" And r.HasFormula = False Then
                If IsNumeric(v) Then
                    r.Clear
                    r.Value = v
                End If
            End If
        End If
    Next r
End Sub



回答2:


You can do this without code, or with quicker code avoiding loops

Manual

  1. Copy a blank cell
  2. Select your range B6:T100001
  3. Press F5. Then Goto ... Special
  4. check Constants and then Text
  5. Paste Special Multiply and check Add

This converts text only cells with numbers into numbers, and leaves actual text or formulae alone

Code

Sub Update()
Dim rng1 As Range
On Error Resume Next
Set rng1 = Range("B6:T10000").SpecialCells(xlCellTypeConstants, 2)
On Error Resume Next
If rng1 Is Nothing Then Exit Sub
'presumes last cell in sheet is blank
Cells(Rows.Count, Columns.Count).Copy
rng1.PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd
End Sub



回答3:


here's my version:

Sub Test()

Dim rng as Range, cel as Range

Set rng = Thisworkbook.Sheets("Sheet1").Range("B6:T10000")

For Each cel In rng
    If Not IsError(cel.Value) Then _
        If Len(cel.Value) <> 0 And cel.HasFormula = False And _
            IsNumeric(cel.Value) Then cel.Value = Val(cel.Value)
Next cel

End Sub

I've tested it, and works fine.
Hope this helps.




回答4:


ActiveSheet.Range("b5:b6004,h5:h6004").Select    
For Each xCell In Selection    
If IsNumeric(xCell) = False Then    
    xCell.Value = Val(xCell.Value)    
Else    
End If    
Next xCell


来源:https://stackoverflow.com/questions/20408689/vba-to-convert-texts-to-numbers-except-formula-and-non-numeric-texts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!