2016-08-01 65 views
-2

在EXCEL VBA中,我如何將一個整數分隔成可以數學運算的單個數字,例如: (1 * 8),(2 * 16),(3 * 32)等分解爲1,2,3,4,5,6,7,8,9的整數123456789; 1 * 8,2 * 16,3 * 32僅僅是例子,實際的乘數可以是不同的,例如, 1 * 1024,2 * 2048等。初始整數(123456789)是來自VBA項目中另一個模塊的變量(id)。如果我沒有清楚解釋,我表示歉意。抱歉格式(這是我在stackoverflow上的第一篇文章)。如何將一個整數分隔爲數字

Option Explicit 
Sub NUMalpha() 

Private Property Get num() As Integer 
    NUMlong = Int(id) 
End Property 

Dim Digit_1 As Integer 

Dim Digit_2 As Integer 

Dim Digit_3 As Integer 

Dim Digit_4 As Integer 

Dim Digit_5 As Integer 

Dim Digit_6 As Integer 

Dim Digit_7 As Integer 

Dim Digit_8 As Integer 

Dim Digit_9 As Integer 

Digit_1 = left(NUMlong, 1) 

Digit_2 = Mid(NUMlong, 2, 1) 

Digit_3 = Mid(NUMlong, 3, 1) 

Digit_4 = Mid(NUMlong, 4, 1) 

Digit_5 = Mid(NUMlong, 5, 1) 

Digit_6 = Mid(NUMlong, 6, 1) 

Digit_7 = Mid(NUMlong, 7, 1) 

Digit_8 = Mid(NUMlong, 8, 1) 

Digit_9 = right(NUMlong, 1) 

End Property 

End Sub 
+1

查找長度或字符串。然後使用中間函數,從1到1的字符串長度進行for循環,每次讀取1個字符。使用循環來定位您正在閱讀的字符。然後,您可以將單個字符分配給變量以進行數學操作,也可以在循環中執行數學操作並保持結果的總計。這將取決於數學是什麼。 –

+0

嗨戴夫。我不清楚你在哪裏得到1 * 8 2 * 16等,請嘗試更清楚地解釋這一點。 –

+1

你到目前爲止嘗試過哪些編碼? –

回答

0

VBA溶液

Sub test() 
    Dim sNum As string, i As Long, mulitp As Variant, aryNum As Variant 

    sNum = Format(Range("A1").Value, "0") 
    mulitp = 8 
    ReDim aryNum(1 To Len(sNum)) As Variant 

    For i = 1 To Len(sNum) 
     aryNum(i) = Mid(sNum, i, 1) * mulitp * 2^(i - 1) 
    Next i 

    MsgBox Application.Sum(aryNum) 
End Sub 

工作表式解

使用下面的公式 =SUMPRODUCT(MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1)*1,8*2^(ROW(INDIRECT("1:"&LEN(A1)))-1))

這不是一個陣列式,所以按進入,不 ctrl + shift + enter

enter image description here

0

123456789大於最大整數大小(-32,768至32,767)值在VBA大。

Sub SplitLong() 

    Dim digits() As Long 
    Dim intValue As Long 
    Dim i As Long 
    Dim strValue As String 

    intValue = 123456789 
    strValue = intValue 

    ReDim digits(Len(strValue) - 1) As Long 
    For i = 1 To Len(strValue) 
     digits(i - 1) = Mid$(strValue, i, 1) 
    Next 

End Sub 
相關問題