如何将存储为文本的数字转换为数字?
我尝试过设置:
ActiveSheet.Range("H154").NumberFormat = "General"
但它不起作用!
我发现工作的唯一内容是使用“文本到列”或单击单元格进行编辑,然后单击回车。
但我真的想找到一种方法,使用VBA将存储为文本的工作表中的数字单元格转换为数字。
答案 0 :(得分:4)
一般技术是复制PasteSpecial,乘以1
在代码中,类似这样:
Sub ConvertToNumber()
Dim rng As Range
Dim cl As Range
Dim rConst As Range
' pick an unused cell
Set rConst = Cells(1, 4)
rConst = 1
Set rng = Cells.SpecialCells(xlCellTypeConstants)
rng.NumberFormat = "General"
rConst.Copy
rng.PasteSpecial xlPasteValues, xlPasteSpecialOperationMultiply
rConst.Clear
End Sub
答案 1 :(得分:2)
我不是编码专家,“存储为文本的数字”错误困扰了我很长一段时间。
我终于找到了这个: Delimited Text-to-Columns in a Macro
让我这样:
Sub ConvertTextToNumber()
Sheets("Worksheet_Name").Select
Range("A1").Select
Selection.TextToColumns _
Destination:=Range("A:A"), _
DataType:=xlDelimited
End Sub
我在宏中使用它来复制&重新排序新工作表中的列:
Sub ColumnReorder()
'**********************************************************
'Paste this macro into the Workbook of each new "Employee_List_Weekly_Update"
'Functionality:
'1. Column order in the "Employee_List_Weekly_Update" worksheet changes fairly often.
' The macro will find each column by header name,
' select that column and copy it to the new sheet.
'2. The macro also converts "Employee ID#" to a number,
' removing the "Number saved as Text" error.
'**********************************************************
'Create new sheet
Sheets.Add.Name = "Roster_Columns_Reordered"
'Repeat for each column or range
'Find Column in "Employee_List_Weekly_Update" - Copy it - Paste it in "Roster_Columns_Reordered" - Employee ID#
Dim a As Integer
Sheets("Employee_List_Weekly_Update").Select
Set rngData = Range("A1").CurrentRegion
a = Application.WorksheetFunction.Match("Employee ID#", Range("A1:BB1"), 0)
Columns(a).Select
Selection.Copy
Sheets("Roster_Columns_Reordered").Select
Range("A1").Select
ActiveSheet.Paste
'Use TextToColumns to convert "Number Stored as Text "
Selection.TextToColumns _
Destination:=Range("A:A"), _
DataType:=xlDelimited
'Find Column in "Employee_List_Weekly_Update" - Copy it - Paste it in "Roster_Columns_Reordered" - Name
Dim b As Integer
Sheets("Employee_List_Weekly_Update").Select
Set rngData = Range("A1").CurrentRegion
b = Application.WorksheetFunction.Match("Name", Range("A1:BB1"), 0)
Columns(b).Select
Selection.Copy
Sheets("Roster_Columns_Reordered").Select
Range("B1").Select
ActiveSheet.Paste
'Go to "Roster_Columns_Reordered" - Add AutoFilter - Freeze Top Row
Rows("1:1").Select
Selection.AutoFilter
With ActiveWindow
.SplitColumn = 2
.SplitRow = 1
End With
Rows("2:2").Select
ActiveWindow.FreezePanes = True
Range("A1").Select
End Sub
答案 2 :(得分:1)
只需使用CDbl()
:
ActiveSheet.Range("H154") = CDbl(ActiveSheet.Range("H154"))
答案 3 :(得分:1)
如果你想转换一个选择(甚至包含文本!),你可以使用firefiend(http://www.ozgrid.com/forum/showthread.php?t=64027&p=331498#post331498)的代码
我认为魔术在.Value = .Value
vba
Sub macro()
Range("F:F").Select 'specify the range which suits your purpose
With Selection
.NumberFormat = "General"
.Value = .Value
End With
End Sub