2017-06-06 88 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

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