2011-06-01 77 views
44

我需要將從VBA中獲取的字符串從excel中轉​​換爲整數。爲此,我使用了CInt(),它運行良好。但是有機會的話,該字符串可能比許多其他的東西,在這種情況下,我需要設置整數爲0。目前我有:vba將字符串轉換爲int如果字符串是數字

If oXLSheet2.Cells(4, 6).Value <> "example string" Then 
    currentLoad = CInt(oXLSheet2.Cells(4, 6).Value) 
Else 
    currentLoad = 0 
End If 

的問題是,我無法預測所有可能的非數字可能在這個單元格中的字符串。有沒有一種方法可以告訴它轉換,如果它是一個整數,並設置爲0,如果不是?

乾杯 帽

回答

76

使用則IsNumeric。如果它是一個數字,則返回true,否則返回false。

Public Sub NumTest() 
    On Error GoTo MyErrorHandler 

    Dim myVar As Variant 
    myVar = 11.2 'Or whatever 

    Dim finalNumber As Integer 
    If IsNumeric(myVar) Then 
     finalNumber = CInt(myVar) 
    Else 
     finalNumber = 0 
    End If 

    Exit Sub 

MyErrorHandler: 
    MsgBox "NumTest" & vbCrLf & vbCrLf & "Err = " & Err.Number & _ 
     vbCrLf & "Description: " & Err.Description 
End Sub 
+3

即使IsNumeric返回True,CInt仍可能因溢出而失敗 - 特別是對於小於-32768或大於32767的數字。 – 2011-06-01 14:32:12

+1

爲避免溢出問題,您可以使用Int或Fix而不是CInt,儘管它們的行爲是在處理非整數十進制數時會略有不同--Cnt回合,而Int向下截斷(遠離零),Fix向上截斷(向零)。 – 2011-06-01 14:38:03

+4

作爲使用IsNumeric的替代方法,您可以簡單地以默認值0開始,嘗試使用Int轉換提供的值,並忽略任何錯誤,如下所示:'Public Function IntOrZero(ByVal vValue As Variant)As Double | IntOrZero = 0 | On Error Resume Next | IntOrZero = Int(vValue)| End Function' - 只需替換|換行符。 – 2011-06-01 14:43:44

0

把它放在一個行:

currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0) 
2

試試這個: currentLoad = ConvertToLongInteger(oXLSheet2.Cells(4, 6).Value) 使用此項功能:

Function ConvertToLongInteger(ByVal stValue As String) As Long 
On Error GoTo ConversionFailureHandler 
ConvertToLongInteger = CLng(stValue) 'TRY to convert to an Integer value 
Exit Function   'If we reach this point, then we succeeded so exit 

ConversionFailureHandler: 
'IF we've reached this point, then we did not succeed in conversion 
'If the error is type-mismatch, clear the error and return numeric 0 from the function 
'Otherwise, disable the error handler, and re-run the code to allow the system to 
'display the error 
If Err.Number = 13 Then 'error # 13 is Type mismatch 
     Err.Clear 
     ConvertToLongInteger = 0 
     Exit Function 
Else 
     On Error GoTo 0 
     Resume 
End If 
End Function 

我選擇龍(整數),而不是簡單的整型的,因爲整數在VBA中的最小/最大大小很差(最小值:-32768,最大值:+32767)。在電子表格操作中,通常在該範圍外有一個整數。

上面的代碼可以修改爲處理從字符串到整數,到貨幣(使用CCur()),到十進制(使用CDec()),到雙(使用CDbl())等的轉換。只需要替換轉換函數本身(CLng)。更改函數返回類型,並重命名函數變量的所有匹配項以使所有內容保持一致。

-1

這裏有三個可能有用的功能。首先檢查字符串是否爲正確的數字格式,第二個和第三個函數將字符串轉換爲Long或Double。

Function IsValidNumericEntry(MyString As String) As Boolean 
'******************************************************************************** 
'This function checks the string entry to make sure that valid digits are in the string. 
'It checks to make sure the + and - are the first character if entered and no duplicates. 
'Valid charcters are 0 - 9, + - and the . 
'******************************************************************************** 
Dim ValidEntry As Boolean 
Dim CharCode As Integer 
Dim ValidDigit As Boolean 
Dim ValidPlus As Boolean 
Dim ValidMinus As Boolean 
Dim ValidDecimal As Boolean 
Dim ErrMsg As String 

ValidDigit = False 
ValidPlus = False 
ValidMinus = False 
ValidDecimal = False 

ValidEntry = True 
For x = 1 To Len(MyString) 
    CharCode = Asc(Mid(MyString, x, 1)) 
    Select Case CharCode 

    Case 48 To 57 ' Digits 0 - 9 
     ValidDigit = True 

    Case 43 ' Plus sign 

    If ValidPlus Then 'One has already been detected and this is a duplicate 
     ErrMsg = "Invalid entry....too many plus signs!" 
     ValidEntry = False 
     Exit For 
    ElseIf x = 1 Then 'if in the first positon it is valide 
     ValidPlus = True 
    Else 'Not in first position and it is invalid 
     ErrMsg = "Invalide entry....Plus sign not in the correct position! " 
     ValidEntry = False 
     Exit For 
    End If 

    Case 45 ' Minus sign 

    If ValidMinus Then 'One has already been detected and this is a duplicate 
     ErrMsg = "Invalide entry....too many minus signs! " 
     ValidEntry = False 
     Exit For 
    ElseIf x = 1 Then 'if in the first position it is valid 
     ValidMinus = True 
    Else 'Not in first position and it is invalid 
     ErrMsg = "Invalide entry....Minus sign not in the correct position! " 
     ValidEntry = False 
     Exit For 
    End If 

    Case 46 ' Period 

    If ValidDecimal Then 'One has already been detected and this is a duplicate 
     ErrMsg = "Invalide entry....too many decimals!" 
     ValidEntry = False 
     Exit For 
    Else 
     ValidDecimal = True 
    End If 

    Case Else 
     ErrMsg = "Invalid numerical entry....Only digits 0-9 and the . + - characters are valid!" 
     ValidEntry = False 
     Exit For 

    End Select 

Next 

    If ValidEntry And ValidDigit Then 
     IsValidNumericEntry = True 
    Else 
     If ValidDigit = False Then 
      ErrMsg = "Text string contains an invalid numeric format." & vbCrLf _ 
      & "Use only one of the following formats!" & vbCrLf _ 
      & "(+dd.dd -dd.dd +dd -dd dd.d or dd)! " 
     End If 
     MsgBox (ErrMsg & vbCrLf & vbCrLf & "You Entered: " & MyString) 
     IsValidNumericEntry = False 
    End If 

End Function 

Function ConvertToLong(stringVal As String) As Long 
'Assumes the user has verified the string contains a valide numeric entry. 
'User should call the function IsValidNumericEntry first especially after any user input 
'to verify that the user has entered a proper number. 

ConvertToLong = CLng(stringVal) 


End Function 
Function ConvertToDouble(stringVal As String) As Double 
'Assumes the user has verified the string contains a valide numeric entry. 
'User should call the function IsValidNumericEntry first especially after any user input 
'to verify that the user has entered a proper number. 

    ConvertToDouble = CDbl(stringVal) 

End Function 
+1

第一個函數具有相當特殊的格式要求,使其與其他答案的問題差不多相關。第二和第三個函數不應該被使用,因爲他們所做的只是調用一個vba函數,而要求一個較窄的變量。將它們稱爲「ConvertStringToDouble」或「ConvertStringToLong」會更合理,這使得它更清晰,爲什麼它不增加任何價值。 – 2012-08-29 19:23:47

+0

第一個功能是特定的,它檢查以確保沒有其他字符或打字錯誤輸入(我有問題與人輸入額外的字符),所以這只是檢查,以確保該字符串可以通過CDbl或CLng函數轉換而不吹啓動或返回不正確的值。正在使用這些調試功能時糾正餘下的問題。除非你總是假設字符串格式正確,否則在轉換字符串之前,可以在這兩個字符串中檢查有效的數字調用......我從不假設。感謝您的評論。 – Doug 2012-08-29 21:28:57

4

強制轉爲或轉換爲int,注意以下事項。

這些函數是Excel VBA中取決於系統區域設置的視圖函數之一。因此,如果您在歐洲某些國家/地區使用雙倍逗號,則會在美國遇到錯誤。

例如,在歐洲的Excel版本0.5將與CDbl()表現良好,但在美國的版本,它會導致5 因此,我建議使用以下選擇:

Public Function CastLong(var As Variant) 

    ' replace , by . 
    var = Replace(var, ",", ".")   

    Dim l As Long 
    On Error Resume Next 
    l = Round(Val(var)) 

    ' if error occurs, l will be 0 
    CastLong = l 

End Function 

' similar function for cast-int, you can add minimum and maximum value if you like 
' to prevent that value is too high or too low. 
Public Function CastInt(var As Variant) 

    ' replace , by . 
    var = Replace(var, ",", ".") 

    Dim i As Integer 
    On Error Resume Next 
    i = Round(Val(var)) 

    ' if error occurs, i will be 0 
    CastInt = i 

End Function 

當然,你也可以考慮人們使用逗號和點的情況,例如三千如3,000.00。如果您需要這些類型的功能,那麼您必須檢查另一個解決方案。

+1

另外,美國語言環境中的CLng會將括號中的數字解析爲負數。例如,'CLng(「(123)」)'返回'-123'。參見例如https://support.office.com/en-in/article/Type-Conversion-Functions-8ebb0e94-2d43-4975-bb13-87ac8d1a2202 – cxw 2015-03-17 16:02:00