Thursday, June 28, 2012

STL Files: Reading the Number of Triangles in VBA

The file format for the STL file is described at

It states that the number of triangles is and unsigned 32 bit integer. Unsigned integers are not a native data type in VB. So what needs to be done is convert a Long signed integer into an unsigned integer. Microsoft has a good description of this at

The key function that needs to be used is:

      Private Const OFFSET_4 = 4294967296#

      Function LongToUnsigned(Value As Long) As Double
        If Value < 0 Then
          LongToUnsigned = Value + OFFSET_4
          LongToUnsigned = Value
        End If
      End Function
The code to read the number of triangles then is:
Sub ReadBlockStl()
    Open "C:\Block.STL" For Binary Access Read As #1
    Dim NumOfTrian As Long
    Get #1, 81, NumOfTrian
    Close #1
    MsgBox LongToUnsigned(NumOfTrian)
End Sub

This code worked find on a cube that had 12 triangles.

However, I tried it on an object that 33924 triangles and I got an overflow error on a for-loop for NumOfTrian. Of course, NumOfTrian is a Long with a maximum positive value of 32768. But when I used a double precission, I still get the same overflow error.

No comments:

Post a Comment

Solidworks macros eith ChatGPT

 Record a simple using thr Solidworks macro recorder, upload it to ChatGPT, and explain to ChatGPT how you want it changed:  https://youtu.b...