2017-06-06 94 views
-4

我想知道如何在Excel VBA中使用bitconverter方法。 我想使用BitConverter.ToInt32將每個放置在32位整數中的差分單元中的4個字節轉換。VBA位轉換器

有人可以幫我一個在VBA中使用的例子嗎?我認爲我在語法上掙扎。

由於

+0

'我想4個字節轉換成32位integer'和'我想4個字節轉換成在使用VBA' BitConverter.ToInt32一個32位的整數。[兩個不同的問題](HTTPS ://meta.stackexchange.com/q/66377/147640)。你想做什麼 - 找到一種方法從VBA中調用.NET的'BitConverter'方法或在VBA中將4個字節轉換爲一個int? – GSerg

+0

感謝您的回答!我的最終目標是在VBA中將4個字節轉換爲一個int。我認爲最實用的方法是調用.NET的BitConverter,但如果還有其他路徑,我也很樂意學習 – KarmaWin

+0

如果你想調用.NET的'BitConverter',然後查找如何從VBA調用.NET代碼,不要求人們爲你寫代碼。 –

回答

2
  • 隨着CopyMemory

    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long) 
    
    Public Function BytesToLong(b() As Byte) As Long 
        CopyMemory BytesToLong, b(LBound(b)), 4 
    End Function 
    
  • CopyMemory 1:

    Private Type thebytes 
        b(1 To 4) As Byte 
    End Type 
    
    Private Type thelong 
        l As Long 
    End Type 
    
    
    Public Function BytesToLong(b() As Byte) As Long 
        Dim tb As thebytes, tl As thelong 
        Dim lb As Long 
    
        lb = LBound(b) 
        tb.b(1) = b(lb) 
        tb.b(2) = b(lb + 1) 
        tb.b(3) = b(lb + 2) 
        tb.b(4) = b(lb + 3) 
    
        LSet tl = tb 
    
        BytesToLong = tl.l 
    End Function 
    
  • 沒有CopyMemory 2:

    Public Function BytesToLong(b() As Byte) As Long 
        Dim lb As Long 
        lb = LBound(b) 
    
        If (b(lb + 3) And &H80) = &H80 Then 
        BytesToLong = (b(lb) + b(lb + 1) * &H100& + b(lb + 2) * &H10000 + (b(lb + 3) And Not &H80) * &H1000000) Or &H80000000 
        Else 
        BytesToLong = b(lb) + b(lb + 1) * &H100& + b(lb + 2) * &H10000 + b(lb + 3) * &H1000000 
        End If 
    
    End Function 
    
+1

不錯spoonfeeder答案......肯定會upvote,如果這是一個體面的問題。 –

+0

@ Mat'sMug我盡力不回答,但似乎沒有適當的重複,除了https://stackoverflow.com/q/7801080/11683和https://stackoverflow.com/q/15782705/11683,所以我想,無論如何。我已提高您的評論。 – GSerg

+1

呃,到底是什麼,反正=) –