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

VBA Excel to Double Click change to checkmark or x

 Note that to do this, you need to set the font of the affected cells to Winding 2 first: 1 2 3 4 5 6 7 8 9 10 11 12 Private Sub Worksheet...