VBA如何将整数拆分为单独的部分

时间:2013-11-29 13:28:43

标签: excel vba excel-vba split integer

我在Excel中使用VBA。 我需要将整数分成两部分,特别是前两位和后两位。 这些数字最多有四位数,至少有一位数。 (我已经整理出空白值)例如。

7应该变为0和7,

23应该变为0和23,

642应该变成6和42,

1621应该变成16和21。

这是我到目前为止的代码

Function Bloog(value1 As Integer)

Dim value1Hours, value1Mins As Integer

Select Case Len(value1) 'gives a number depending on the length of the value1
    Case 1, 2 ' e.g., 2 = 0, 2 or 16 = 0, 16
        value1Hours = 0
        value1Mins = value1
    Case 3 ' e.g., 735 = 7, 35
        value1Hours = Left(value1, 1) ' 7
        value1Mins = Right(value1, 2) ' 35
    Case 4 ' e.g., 1234 = 12, 34
        value1Hours = Left(value1, 2) ' 12
        value1Mins = Right(value1, 2) ' 34
End Select

然而,当获取值时,我发现它们没有被分成单独的部分,因为Left()和Right()函数会让我相信。 Len()似乎也没有工作,当它被赋予值723时,它返回的长度为2.

任何提示将不胜感激。

=======================================

在建议之后我将值转换为字符串,然后完成case语句并在之后将它们转换回来。 (因为我需要它们进行一些计算)

Private Function Bloog(value1 As Integer) As Integer

Dim strValue1 As String
Dim strValue1Hours, strValue1Mins As String
Dim value1Hours, value1Mins As Integer

'converts the values into strings for the Left() and Right() functions
strValue1 = CStr(value1)

Select Case Len(value1) 'gives a number depending on the length of the value1
    Case 1, 2 ' e.g., 2 = 0, 2 or 16 = 0, 16
        strValue1Hours = 0
        strValue1Mins = value1
    Case 3 ' e.g., 735 = 7, 35
        strValue1Hours = Left(value1, 1) ' 7
        strValue1Mins = Right(value1, 2) ' 35
    Case 4 ' e.g., 1234 = 12, 34
        strValue1Hours = Left(value1, 2) ' 12
        strValue1Mins = Right(value1, 2) ' 34
End Select

value1Hours = CInt(strValue1Hours)
value1Mins = CInt(strValue1Mins)

Len()仍然认为字符串的长度为2,因此触发了case 2语句,尽管strValue1Mins和value1Mins仍然等于832。

=======================

Len()正在测试Value1而不是strValue1,之后一切正常。

3 个答案:

答案 0 :(得分:3)

value1是一个整数,为什么不使用算术运算?

Dim value1Hours as Integer,value1Mins as Integer
value1Mins = value1 Mod 100
value1Hours = Int(value1 / 100)

答案 1 :(得分:2)

希望这会有所帮助。这是我能想到的最简单的方式。

ValueAsString = Right("0000" & value1,4)
strValue1Hours = Left(ValueAsString, 2)
strValue1Mins = Right(ValueAsString, 2)

答案 2 :(得分:2)

为了它的价值:

    value1Hours = CInt(Left(Format(x, "0000"), 2))
    value1Mins = CInt(Right(Format(x, "0000"), 2))
相关问题