programing

문자열이 숫자인 경우 문자열을 int로 변환

oldcodes 2023. 5. 24. 22:21
반응형

문자열이 숫자인 경우 문자열을 int로 변환

엑셀에서 얻은 문자열을 VBA에서 정수로 변환해야 합니다.내가 사용하는 방법CInt()잘 작동하는 것.그러나 문자열이 숫자가 아닐 수도 있습니다. 이 경우 정수를 0으로 설정해야 합니다.현재 사용자:

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

문제는 이 셀에 있을 수 있는 모든 비숫자 문자열을 예측할 수 없다는 것입니다.정수이면 변환하고 없으면 0으로 설정하라고 할 수 있는 방법이 있나요?

사용하다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

길게 주조하거나 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)도 생각할 수 있습니다.이러한 경우 기능이 필요한 경우 다른 솔루션을 확인해야 합니다.

사용해 보십시오.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() 사용), 10진수로(CDec() 사용), 2배로(CDbl() 사용) 등의 변환을 처리하도록 수정할 수 있습니다.변환 함수 자체(CLng)만 교체하면 됩니다.함수 반환 유형을 변경하고 모든 항목이 일관되도록 함수 변수의 이름을 변경합니다.

그냥 사용하기Val():

currentLoad = Int(Val([f4]))

지금이다currentLoad정수 값을 가지면 0이 됩니다.[f4]숫자가 아닙니다.

한 줄로 묶기

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

다음은 유용할 수 있는 세 가지 기능입니다.먼저 문자열의 올바른 숫자 형식을 확인하고, 두 번째 및 세 번째 함수는 문자열을 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

언급URL : https://stackoverflow.com/questions/6202074/convert-string-to-int-if-string-is-a-number

반응형