2016-04-21 4824 views
4

我有幾列數字,無論出於何種原因,都被格式化爲文本。這可以防止我使用諸如小計功能之類的算術函數。將這些「文本數字」轉換爲真實數字的最佳方式是什麼?VBA:將文本轉換爲數字

下面是具體問題的截圖: Error

我已經試過這些片段無濟於事:

Columns(5).NumberFormat = "0" 

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
     :=False, Transpose:=False 
+2

突出顯示所有的數字。點擊警告框旁邊的向下箭頭。選擇轉換爲數字。它將在不需要vba的情況下進行大規模部署。 –

+0

嗨斯科特 - 我同意這是一個很好的解決方案。但是,我現在可以聽到最終用戶抱怨說「一切都是零!」已經。由於VBA已經被用於運行腳本(我應該在這個問題中提到這一點),在我看來,最好只包括代碼來避免這個對話。 – aLearningLady

+0

使用CInt(Cell()。Value)將單元格的值作爲數字 – gizlmo

回答

5

使用下面的函數(改變[E:E]爲適合您需要的範圍)來規避此問題:

[E:E].Select 
With Selection 
    .NumberFormat = "General" 
    .Value = .Value 
End With 
3

我之前有過這個問題,這是我的解決方案。

With Worksheets("Sheet1").Columns(5) 
    .NumberFormat = "0" 
    .Value = .Value 
End With 
1

這將Excel工作簿的所有文本轉換爲數字。

Sub ConvertTextToNumbers() 
Dim wBook As Workbook 
Dim LastRow As Long, LastCol As Long 
Dim Rangetemp As Range 

'Enter here the path of your workbook 
Set wBook = Workbooks.Open("yourWorkbook") 
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 

For c = 1 To LastCol 
Set Rangetemp = Cells(c).EntireColumn 
Rangetemp.TextToColumns DataType:=xlDelimited, _ 
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ 
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _ 
    :=Array(1, 1), TrailingMinusNumbers:=True 
Next c 
End Sub 
3

這可以用於查找表單中的所有數值(甚至那些格式爲文本)並將它們轉換爲單個(CSng函數)。

For Each r In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeConstants) 
    If IsNumeric(r) Then 
     r.Value = CSng(r.Value) 
     r.NumberFormat = "0.00" 
    End If 
Next 
0

爲我的作品是解決方案:

For Each xCell In Selection 

    xCell.Value = CDec(xCell.Value) 

Next xCell