CadPaste

SolidWorks

VBA macros for SolidWorks.

Press / to focus search.

SolidWorks · VBA · 5 days ago

DXF Color REMAP

После экспорта DXF будет содержать 2 вида цветов - RGB и ColorMap.

  • export
VBA
'Attribute VB_Name = "RemapDxfColors"
'==============================================================================
' RemapDxfColors
'
' Export active document to DXF (R2004+), then remap selected RGB colors to
' AutoCAD Color Index (group 62). Unlisted colors stay True Color RGB (420).
'
' Why R2004+: R2000-2002 has no True Color — SW writes only ACI (62).
' RESTORE_UNMAPPED_AS_RGB: SW often exports pure red as 62=1 without 420;
'   restore turns that into RGB so COLOR_MAP can still create a second "Red"
'   as ACI (e.g. black 0,0,0=1) alongside RGB(255,0,0).
'
' COLOR_MAP: R,G,B=ACI  (only colors that become index 62)
' ACI: 1 Red  2 Yellow  3 Green  4 Cyan  5 Blue
'      6 Magenta  7 White/Black  8 Dark gray  9 Light gray
'==============================================================================
Option Explicit

'----- USER SETTINGS ----------------------------------------------------------
' Right side = ACI from list above. Several entries separated by |
Private Const COLOR_MAP As String = "0,0,0=1|10,10,10=1"

' True  = lone ACI 1..9 (no following 420) -> RGB 420 (two "reds" possible)
' False = leave those ACI untouched
Private Const RESTORE_UNMAPPED_AS_RGB As Boolean = True

' DXF version on export:
'   0 keep SW setting  1 R13  2 R14  3 R2000-2002 (no RGB)
'   4 R2004-2006 (recommended)  5 R2007  6 R2010  7 R2013  8 R2018
Private Const FORCE_DXF_VERSION As Long = 4

Private Const FALLBACK_FOLDER As String = "C:\Temp"
Private Const MAKE_BACKUP As Boolean = True
'------------------------------------------------------------------------------

Private mapRgb() As Long, mapRgbAci() As Long, mapRgbN As Long
Private mapAciSrc() As Long, mapAciDst() As Long, mapAciN As Long
Private nToAci As Long, nToRgb As Long
' Packed RGB values already present as group 420 (filled before remap pass)
Private have420() As Long, have420N As Long

Sub main()
    Dim swApp As SldWorks.SldWorks, swModel As ModelDoc2
    Dim dxfPath As String, n As Long, errMsg As String

    On Error GoTo Fail
    If Not ParseColorMap(COLOR_MAP, errMsg) Then
        MsgBox "COLOR_MAP error:" & vbCrLf & errMsg, vbExclamation, "RemapDxfColors": Exit Sub
    End If
    If mapRgbN < 1 Then
        MsgBox "COLOR_MAP is empty. Example: 0,0,0=1", vbExclamation, "RemapDxfColors": Exit Sub
    End If

    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "Open a SolidWorks document first.", vbExclamation, "RemapDxfColors": Exit Sub
    End If

    dxfPath = ExportActiveToDxf(swApp, swModel)
    If Len(dxfPath) = 0 Then Exit Sub

    n = RemapDxfFile(dxfPath)
    MsgBox "DXF: " & dxfPath & vbCrLf & vbCrLf & _
           "Changes: " & n & "  (to ACI: " & nToAci & ", to RGB: " & nToRgb & ")" & vbCrLf & _
           "COLOR_MAP entries: " & mapRgbN & _
           IIf(n = 0, vbCrLf & vbCrLf & "No matches — use R2004+ and exact SW RGB.", ""), _
           vbInformation, "RemapDxfColors"
    Exit Sub
Fail:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "RemapDxfColors"
End Sub

' Build RGB->ACI and nearest-ACI->ACI tables from "R,G,B=ACI|..."
Private Function ParseColorMap(ByVal s As String, ByRef errMsg As String) As Boolean
    Dim parts() As String, i As Long, p As Long
    Dim leftP As String, rightP As String, rgb() As String
    Dim r As Long, g As Long, b As Long, aci As Long

    errMsg = "": mapRgbN = 0: mapAciN = 0
    s = Replace(Replace(Trim$(s), vbCr, ""), vbLf, "")
    If Len(s) = 0 Then ParseColorMap = True: Exit Function

    parts = Split(s, "|")
    ReDim mapRgb(0 To UBound(parts)): ReDim mapRgbAci(0 To UBound(parts))
    ReDim mapAciSrc(0 To UBound(parts)): ReDim mapAciDst(0 To UBound(parts))

    For i = 0 To UBound(parts)
        leftP = Trim$(parts(i)): If Len(leftP) = 0 Then GoTo nxt
        p = InStr(1, leftP, "=")
        If p < 2 Then errMsg = "Need R,G,B=ACI: " & leftP: Exit Function
        rightP = Trim$(Mid$(leftP, p + 1)): leftP = Trim$(Left$(leftP, p - 1))
        rgb = Split(leftP, ",")
        If UBound(rgb) <> 2 Or Not (IsNumeric(rgb(0)) And IsNumeric(rgb(1)) And IsNumeric(rgb(2)) And IsNumeric(rightP)) Then
            errMsg = "Bad entry: " & parts(i): Exit Function
        End If
        r = CLng(Val(rgb(0))): g = CLng(Val(rgb(1))): b = CLng(Val(rgb(2))): aci = CLng(Val(rightP))
        If r < 0 Or r > 255 Or g < 0 Or g > 255 Or b < 0 Or b > 255 Or aci < 1 Or aci > 255 Then
            errMsg = "Out of range: " & parts(i): Exit Function
        End If
        mapRgb(mapRgbN) = r * 65536# + g * 256# + b: mapRgbAci(mapRgbN) = aci: mapRgbN = mapRgbN + 1
        AddAciRule NearestAci(r, g, b), aci
nxt: Next i

    If mapRgbN > 0 Then ReDim Preserve mapRgb(0 To mapRgbN - 1): ReDim Preserve mapRgbAci(0 To mapRgbN - 1)
    If mapAciN > 0 Then ReDim Preserve mapAciSrc(0 To mapAciN - 1): ReDim Preserve mapAciDst(0 To mapAciN - 1)
    ParseColorMap = True
End Function

Private Sub AddAciRule(ByVal src As Long, ByVal dst As Long)
    Dim i As Long
    If src < 1 Or src > 255 Or src = dst Then Exit Sub
    For i = 0 To mapAciN - 1
        If mapAciSrc(i) = src Then mapAciDst(i) = dst: Exit Sub
    Next i
    mapAciSrc(mapAciN) = src: mapAciDst(mapAciN) = dst: mapAciN = mapAciN + 1
End Sub

' ACI SW usually writes when it does not keep True Color for this RGB.
Private Function NearestAci(ByVal r As Long, ByVal g As Long, ByVal b As Long) As Long
    If r <= 5 And g <= 5 And b <= 5 Then NearestAci = 7: Exit Function
    If r >= 250 And g <= 5 And b <= 5 Then NearestAci = 1: Exit Function
    If r >= 250 And g >= 250 And b <= 5 Then NearestAci = 2: Exit Function
    If r <= 5 And g >= 250 And b <= 5 Then NearestAci = 3: Exit Function
    If r <= 5 And g >= 250 And b >= 250 Then NearestAci = 4: Exit Function
    If r <= 5 And g <= 5 And b >= 250 Then NearestAci = 5: Exit Function
    If r >= 250 And g <= 5 And b >= 250 Then NearestAci = 6: Exit Function
    NearestAci = 7
End Function

Private Function LookupRgb(ByVal packed As Long) As Long
    Dim i As Long
    For i = 0 To mapRgbN - 1
        If mapRgb(i) = packed Then LookupRgb = mapRgbAci(i): Exit Function
    Next i
    LookupRgb = -1
End Function

Private Function LookupAci(ByVal src As Long) As Long
    Dim i As Long
    For i = 0 To mapAciN - 1
        If mapAciSrc(i) = src Then LookupAci = mapAciDst(i): Exit Function
    Next i
    LookupAci = -1
End Function

' Standard ACI 1..9 -> packed RGB for restore. -1 if out of range.
Private Function AciToPackedRgb(ByVal aci As Long) As Long
    Select Case aci
        Case 1: AciToPackedRgb = 16711680      ' 255,0,0
        Case 2: AciToPackedRgb = 16776960      ' 255,255,0
        Case 3: AciToPackedRgb = 65280         ' 0,255,0
        Case 4: AciToPackedRgb = 65535         ' 0,255,255
        Case 5: AciToPackedRgb = 255           ' 0,0,255
        Case 6: AciToPackedRgb = 16711935      ' 255,0,255
        Case 7: AciToPackedRgb = 16777215      ' 255,255,255
        Case 8: AciToPackedRgb = 8421504       ' 128,128,128
        Case 9: AciToPackedRgb = 12632256      ' 192,192,192
        Case Else: AciToPackedRgb = -1
    End Select
End Function

Private Sub WritePair(ByVal ts As Object, ByVal code As Long, ByVal value As String)
    ts.WriteLine Right$(Space$(3) & CStr(code), 3)
    If code = 62 Then ts.WriteLine Right$(Space$(6) & value, 6) Else ts.WriteLine value
End Sub

Private Function ExportActiveToDxf(ByVal swApp As SldWorks.SldWorks, ByVal swModel As ModelDoc2) As String
    Dim pathDoc As String, folder As String, baseName As String, dxfPath As String
    Dim nErrors As Long, nWarnings As Long, ok As Boolean
    Dim fso As Object, swDraw As DrawingDoc

    Const swSaveAsCurrentVersion As Long = 0, swSaveAsOptions_Silent As Long = 1
    Const swDocDRAWING As Long = 3, swExportToDWG_ExportCurrentSheet As Long = 1
    Const swDxfVersion As Long = 60   ' swUserPreferenceIntegerValue_e.swDxfVersion

    If FORCE_DXF_VERSION > 0 Then
        On Error Resume Next: swApp.SetUserPreferenceIntegerValue swDxfVersion, FORCE_DXF_VERSION: On Error GoTo 0
    End If

    pathDoc = swModel.GetPathName
    If Len(pathDoc) > 0 Then
        folder = Left$(pathDoc, InStrRev(pathDoc, "\") - 1)
        baseName = Mid$(pathDoc, InStrRev(pathDoc, "\") + 1)
        If InStrRev(baseName, ".") > 0 Then baseName = Left$(baseName, InStrRev(baseName, ".") - 1)
    Else
        folder = FALLBACK_FOLDER
        baseName = swModel.GetTitle
        If Right$(baseName, 2) = " *" Then baseName = Left$(baseName, Len(baseName) - 2)
    End If
    dxfPath = folder & "\" & baseName & ".dxf"

    Set fso = CreateObject("Scripting.FileSystemObject")
    If Len(folder) > 0 And Not fso.FolderExists(folder) Then fso.CreateFolder folder
    If fso.FileExists(dxfPath) Then On Error Resume Next: fso.DeleteFile dxfPath, True: On Error GoTo 0

    ' No SaveAs Copy with DXF — often False with Errors=0
    If swModel.GetType = swDocDRAWING Then
        On Error Resume Next
        Set swDraw = swModel
        ok = swDraw.ExportToDWG2(dxfPath, pathDoc, swExportToDWG_ExportCurrentSheet, True, Empty, False, False)
        If Err.Number <> 0 Then ok = False: Err.Clear
        On Error GoTo 0
        If ok Or DxfOk(fso, dxfPath) Then ExportActiveToDxf = dxfPath: Exit Function
    End If

    On Error Resume Next
    ok = swModel.Extension.SaveAs(dxfPath, swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, nErrors, nWarnings)
    If Err.Number <> 0 Then ok = False: Err.Clear
    On Error GoTo 0
    If ok Or DxfOk(fso, dxfPath) Then ExportActiveToDxf = dxfPath: Exit Function

    On Error Resume Next
    ok = swModel.SaveAs4(dxfPath, swSaveAsCurrentVersion, swSaveAsOptions_Silent, nErrors, nWarnings)
    If Err.Number <> 0 Then ok = False: Err.Clear
    On Error GoTo 0
    If ok Or DxfOk(fso, dxfPath) Then ExportActiveToDxf = dxfPath: Exit Function

    MsgBox "DXF export failed: " & dxfPath & vbCrLf & "Errors=" & nErrors & " Warnings=" & nWarnings, _
           vbExclamation, "RemapDxfColors"
End Function

Private Function DxfOk(ByVal fso As Object, ByVal path As String) As Boolean
    On Error Resume Next
    If fso.FileExists(path) Then If fso.GetFile(path).Size > 0 Then DxfOk = True
End Function

Private Function IsDestAci(ByVal aci As Long) As Boolean
    Dim i As Long
    For i = 0 To mapRgbN - 1
        If mapRgbAci(i) = aci Then IsDestAci = True: Exit Function
    Next i
End Function

Private Function Has420(ByVal packed As Long) As Boolean
    Dim i As Long
    For i = 0 To have420N - 1
        If have420(i) = packed Then Has420 = True: Exit Function
    Next i
End Function

' Collect existing True Color values so re-run does not undo COLOR_MAP ACI.
Private Sub ScanExisting420(ByVal dxfPath As String)
    Dim fso As Object, ts As Object, c As String, v As String
    have420N = 0: Erase have420
    ReDim have420(0 To 63)
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile(dxfPath, 1, False)
    Do While Not ts.AtEndOfStream
        c = Trim$(ts.ReadLine)
        If ts.AtEndOfStream Then Exit Do
        v = Trim$(ts.ReadLine)
        If c = "420" And IsNumeric(v) Then
            If have420N > UBound(have420) Then ReDim Preserve have420(0 To have420N * 2)
            have420(have420N) = CLng(Val(v)): have420N = have420N + 1
        End If
    Loop
    ts.Close
    If have420N > 0 Then ReDim Preserve have420(0 To have420N - 1)
End Sub

' True when lone ACI should become RGB: not mapped, no following 420,
' and (if this ACI is a COLOR_MAP destination) that RGB is not already in the file.
' Prevents second run from turning mapped ACI Red back into RGB.
Private Function ShouldRestoreAci(ByVal src As Long, ByVal nextIs420 As Boolean) As Boolean
    Dim packed As Long
    If Not RESTORE_UNMAPPED_AS_RGB Or nextIs420 Or src < 1 Or src > 9 Then Exit Function
    If LookupAci(src) >= 1 Then Exit Function
    packed = AciToPackedRgb(src)
    If packed < 0 Then Exit Function
    If IsDestAci(src) And Has420(packed) Then Exit Function
    ShouldRestoreAci = True
End Function

' COLOR_MAP hits -> 62=ACI. Lone unmapped ACI 1..9 -> 420 if RESTORE enabled.
Private Function RemapDxfFile(ByVal dxfPath As String) As Long
    Dim fso As Object, tsIn As Object, tsOut As Object
    Dim tmpPath As String, bakPath As String
    Dim codeLine As String, valLine As String, codeTrim As String, valTrim As String
    Dim peekCode As String, peekVal As String, hasPeek As Boolean, nextIs420 As Boolean
    Dim packed As Long, aci As Long, src As Long, n As Long, hit As Boolean

    nToAci = 0: nToRgb = 0
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FileExists(dxfPath) Then Err.Raise vbObjectError + 1, , "DXF not found: " & dxfPath

    ScanExisting420 dxfPath

    tmpPath = dxfPath & ".tmp": bakPath = dxfPath & ".bak"
    Set tsIn = fso.OpenTextFile(dxfPath, 1, False)
    Set tsOut = fso.OpenTextFile(tmpPath, 2, True)

    n = 0: hasPeek = False
    Do While True
        If hasPeek Then
            codeLine = peekCode: valLine = peekVal: hasPeek = False
        Else
            If tsIn.AtEndOfStream Then Exit Do
            codeLine = tsIn.ReadLine
            If tsIn.AtEndOfStream Then tsOut.WriteLine codeLine: Exit Do
            valLine = tsIn.ReadLine
        End If

        hit = False: codeTrim = Trim$(codeLine): valTrim = Trim$(valLine)

        If codeTrim = "420" And IsNumeric(valTrim) Then
            aci = LookupRgb(CLng(Val(valTrim)))
            If aci >= 1 Then WritePair tsOut, 62, CStr(aci): n = n + 1: nToAci = nToAci + 1: hit = True
        ElseIf codeTrim = "62" And IsNumeric(valTrim) Then
            src = CLng(Val(valTrim))
            If src <> 0 And src <> 256 Then
                nextIs420 = False
                If Not tsIn.AtEndOfStream Then
                    peekCode = tsIn.ReadLine
                    If Not tsIn.AtEndOfStream Then
                        peekVal = tsIn.ReadLine: hasPeek = True
                        If Trim$(peekCode) = "420" Then nextIs420 = True
                    Else
                        tsOut.WriteLine peekCode
                    End If
                End If
                aci = LookupAci(src)
                If aci >= 1 Then
                    WritePair tsOut, 62, CStr(aci): n = n + 1: nToAci = nToAci + 1: hit = True
                ElseIf ShouldRestoreAci(src, nextIs420) Then
                    packed = AciToPackedRgb(src)
                    WritePair tsOut, 420, CStr(packed): n = n + 1: nToRgb = nToRgb + 1: hit = True
                End If
            End If
        End If

        If Not hit Then tsOut.WriteLine codeLine: tsOut.WriteLine valLine
    Loop
    tsIn.Close: tsOut.Close

    If MAKE_BACKUP Then
        If fso.FileExists(bakPath) Then fso.DeleteFile bakPath, True
        fso.CopyFile dxfPath, bakPath, True
    End If
    If fso.FileExists(dxfPath) Then fso.DeleteFile dxfPath, True
    fso.MoveFile tmpPath, dxfPath
    RemapDxfFile = n
End Function
'Attribute VB_Name = "RemapDxfColors"
'==============================================================================
' RemapDxfColors
'
' Export active document to DXF (R2004+), then remap selected RGB colors to
' AutoCAD Color Index (group 62). Unlisted colors stay True Color RGB (420).
'
' Why R2004+: R2000-2002 has no True Color — SW writes only ACI (62).
' RESTORE_UNMAPPED_AS_RGB: SW often exports pure red as 62=1 without 420;
'   restore turns that into RGB so COLOR_MAP can still create a second "Red"
'   as ACI (e.g. black 0,0,0=1) alongside RGB(255,0,0).
'
' COLOR_MAP: R,G,B=ACI  (only colors that become index 62)
' ACI: 1 Red  2 Yellow  3 Green  4 Cyan  5 Blue
'      6 Magenta  7 White/Black  8 Dark gray  9 Light gray
'==============================================================================
Option Explicit

'----- USER SETTINGS ----------------------------------------------------------
' Right side = ACI from list above. Several entries separated by |
Private Const COLOR_MAP As String = "0,0,0=1|10,10,10=1"

' True  = lone ACI 1..9 (no following 420) -> RGB 420 (two "reds" possible)
' False = leave those ACI untouched
Private Const RESTORE_UNMAPPED_AS_RGB As Boolean = True

' DXF version on export:
'   0 keep SW setting  1 R13  2 R14  3 R2000-2002 (no RGB)
'   4 R2004-2006 (recommended)  5 R2007  6 R2010  7 R2013  8 R2018
Private Const FORCE_DXF_VERSION As Long = 4

Private Const FALLBACK_FOLDER As String = "C:\Temp"
Private Const MAKE_BACKUP As Boolean = True
'------------------------------------------------------------------------------

Private mapRgb() As Long, mapRgbAci() As Long, mapRgbN As Long
Private mapAciSrc() As Long, mapAciDst() As Long, mapAciN As Long
Private nToAci As Long, nToRgb As Long
' Packed RGB values already present as group 420 (filled before remap pass)
Private have420() As Long, have420N As Long

Sub main()
    Dim swApp As SldWorks.SldWorks, swModel As ModelDoc2
    Dim dxfPath As String, n As Long, errMsg As String

    On Error GoTo Fail
    If Not ParseColorMap(COLOR_MAP, errMsg) Then
        MsgBox "COLOR_MAP error:" & vbCrLf & errMsg, vbExclamation, "RemapDxfColors": Exit Sub
    End If
    If mapRgbN < 1 Then
        MsgBox "COLOR_MAP is empty. Example: 0,0,0=1", vbExclamation, "RemapDxfColors": Exit Sub
    End If

    Set swApp = Application.SldWorks
    Set swModel = swApp.ActiveDoc
    If swModel Is Nothing Then
        MsgBox "Open a SolidWorks document first.", vbExclamation, "RemapDxfColors": Exit Sub
    End If

    dxfPath = ExportActiveToDxf(swApp, swModel)
    If Len(dxfPath) = 0 Then Exit Sub

    n = RemapDxfFile(dxfPath)
    MsgBox "DXF: " & dxfPath & vbCrLf & vbCrLf & _
           "Changes: " & n & "  (to ACI: " & nToAci & ", to RGB: " & nToRgb & ")" & vbCrLf & _
           "COLOR_MAP entries: " & mapRgbN & _
           IIf(n = 0, vbCrLf & vbCrLf & "No matches — use R2004+ and exact SW RGB.", ""), _
           vbInformation, "RemapDxfColors"
    Exit Sub
Fail:
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "RemapDxfColors"
End Sub

' Build RGB->ACI and nearest-ACI->ACI tables from "R,G,B=ACI|..."
Private Function ParseColorMap(ByVal s As String, ByRef errMsg As String) As Boolean
    Dim parts() As String, i As Long, p As Long
    Dim leftP As String, rightP As String, rgb() As String
    Dim r As Long, g As Long, b As Long, aci As Long

    errMsg = "": mapRgbN = 0: mapAciN = 0
    s = Replace(Replace(Trim$(s), vbCr, ""), vbLf, "")
    If Len(s) = 0 Then ParseColorMap = True: Exit Function

    parts = Split(s, "|")
    ReDim mapRgb(0 To UBound(parts)): ReDim mapRgbAci(0 To UBound(parts))
    ReDim mapAciSrc(0 To UBound(parts)): ReDim mapAciDst(0 To UBound(parts))

    For i = 0 To UBound(parts)
        leftP = Trim$(parts(i)): If Len(leftP) = 0 Then GoTo nxt
        p = InStr(1, leftP, "=")
        If p < 2 Then errMsg = "Need R,G,B=ACI: " & leftP: Exit Function
        rightP = Trim$(Mid$(leftP, p + 1)): leftP = Trim$(Left$(leftP, p - 1))
        rgb = Split(leftP, ",")
        If UBound(rgb) <> 2 Or Not (IsNumeric(rgb(0)) And IsNumeric(rgb(1)) And IsNumeric(rgb(2)) And IsNumeric(rightP)) Then
            errMsg = "Bad entry: " & parts(i): Exit Function
        End If
        r = CLng(Val(rgb(0))): g = CLng(Val(rgb(1))): b = CLng(Val(rgb(2))): aci = CLng(Val(rightP))
        If r < 0 Or r > 255 Or g < 0 Or g > 255 Or b < 0 Or b > 255 Or aci < 1 Or aci > 255 Then
            errMsg = "Out of range: " & parts(i): Exit Function
        End If
        mapRgb(mapRgbN) = r * 65536# + g * 256# + b: mapRgbAci(mapRgbN) = aci: mapRgbN = mapRgbN + 1
        AddAciRule NearestAci(r, g, b), aci
nxt: Next i

    If mapRgbN > 0 Then ReDim Preserve mapRgb(0 To mapRgbN - 1): ReDim Preserve mapRgbAci(0 To mapRgbN - 1)
    If mapAciN > 0 Then ReDim Preserve mapAciSrc(0 To mapAciN - 1): ReDim Preserve mapAciDst(0 To mapAciN - 1)
    ParseColorMap = True
End Function

Private Sub AddAciRule(ByVal src As Long, ByVal dst As Long)
    Dim i As Long
    If src < 1 Or src > 255 Or src = dst Then Exit Sub
    For i = 0 To mapAciN - 1
        If mapAciSrc(i) = src Then mapAciDst(i) = dst: Exit Sub
    Next i
    mapAciSrc(mapAciN) = src: mapAciDst(mapAciN) = dst: mapAciN = mapAciN + 1
End Sub

' ACI SW usually writes when it does not keep True Color for this RGB.
Private Function NearestAci(ByVal r As Long, ByVal g As Long, ByVal b As Long) As Long
    If r <= 5 And g <= 5 And b <= 5 Then NearestAci = 7: Exit Function
    If r >= 250 And g <= 5 And b <= 5 Then NearestAci = 1: Exit Function
    If r >= 250 And g >= 250 And b <= 5 Then NearestAci = 2: Exit Function
    If r <= 5 And g >= 250 And b <= 5 Then NearestAci = 3: Exit Function
    If r <= 5 And g >= 250 And b >= 250 Then NearestAci = 4: Exit Function
    If r <= 5 And g <= 5 And b >= 250 Then NearestAci = 5: Exit Function
    If r >= 250 And g <= 5 And b >= 250 Then NearestAci = 6: Exit Function
    NearestAci = 7
End Function

Private Function LookupRgb(ByVal packed As Long) As Long
    Dim i As Long
    For i = 0 To mapRgbN - 1
        If mapRgb(i) = packed Then LookupRgb = mapRgbAci(i): Exit Function
    Next i
    LookupRgb = -1
End Function

Private Function LookupAci(ByVal src As Long) As Long
    Dim i As Long
    For i = 0 To mapAciN - 1
        If mapAciSrc(i) = src Then LookupAci = mapAciDst(i): Exit Function
    Next i
    LookupAci = -1
End Function

' Standard ACI 1..9 -> packed RGB for restore. -1 if out of range.
Private Function AciToPackedRgb(ByVal aci As Long) As Long
    Select Case aci
        Case 1: AciToPackedRgb = 16711680      ' 255,0,0
        Case 2: AciToPackedRgb = 16776960      ' 255,255,0
        Case 3: AciToPackedRgb = 65280         ' 0,255,0
        Case 4: AciToPackedRgb = 65535         ' 0,255,255
        Case 5: AciToPackedRgb = 255           ' 0,0,255
        Case 6: AciToPackedRgb = 16711935      ' 255,0,255
        Case 7: AciToPackedRgb = 16777215      ' 255,255,255
        Case 8: AciToPackedRgb = 8421504       ' 128,128,128
        Case 9: AciToPackedRgb = 12632256      ' 192,192,192
        Case Else: AciToPackedRgb = -1
    End Select
End Function

Private Sub WritePair(ByVal ts As Object, ByVal code As Long, ByVal value As String)
    ts.WriteLine Right$(Space$(3) & CStr(code), 3)
    If code = 62 Then ts.WriteLine Right$(Space$(6) & value, 6) Else ts.WriteLine value
End Sub

Private Function ExportActiveToDxf(ByVal swApp As SldWorks.SldWorks, ByVal swModel As ModelDoc2) As String
    Dim pathDoc As String, folder As String, baseName As String, dxfPath As String
    Dim nErrors As Long, nWarnings As Long, ok As Boolean
    Dim fso As Object, swDraw As DrawingDoc

    Const swSaveAsCurrentVersion As Long = 0, swSaveAsOptions_Silent As Long = 1
    Const swDocDRAWING As Long = 3, swExportToDWG_ExportCurrentSheet As Long = 1
    Const swDxfVersion As Long = 60   ' swUserPreferenceIntegerValue_e.swDxfVersion

    If FORCE_DXF_VERSION > 0 Then
        On Error Resume Next: swApp.SetUserPreferenceIntegerValue swDxfVersion, FORCE_DXF_VERSION: On Error GoTo 0
    End If

    pathDoc = swModel.GetPathName
    If Len(pathDoc) > 0 Then
        folder = Left$(pathDoc, InStrRev(pathDoc, "\") - 1)
        baseName = Mid$(pathDoc, InStrRev(pathDoc, "\") + 1)
        If InStrRev(baseName, ".") > 0 Then baseName = Left$(baseName, InStrRev(baseName, ".") - 1)
    Else
        folder = FALLBACK_FOLDER
        baseName = swModel.GetTitle
        If Right$(baseName, 2) = " *" Then baseName = Left$(baseName, Len(baseName) - 2)
    End If
    dxfPath = folder & "\" & baseName & ".dxf"

    Set fso = CreateObject("Scripting.FileSystemObject")
    If Len(folder) > 0 And Not fso.FolderExists(folder) Then fso.CreateFolder folder
    If fso.FileExists(dxfPath) Then On Error Resume Next: fso.DeleteFile dxfPath, True: On Error GoTo 0

    ' No SaveAs Copy with DXF — often False with Errors=0
    If swModel.GetType = swDocDRAWING Then
        On Error Resume Next
        Set swDraw = swModel
        ok = swDraw.ExportToDWG2(dxfPath, pathDoc, swExportToDWG_ExportCurrentSheet, True, Empty, False, False)
        If Err.Number <> 0 Then ok = False: Err.Clear
        On Error GoTo 0
        If ok Or DxfOk(fso, dxfPath) Then ExportActiveToDxf = dxfPath: Exit Function
    End If

    On Error Resume Next
    ok = swModel.Extension.SaveAs(dxfPath, swSaveAsCurrentVersion, swSaveAsOptions_Silent, Nothing, nErrors, nWarnings)
    If Err.Number <> 0 Then ok = False: Err.Clear
    On Error GoTo 0
    If ok Or DxfOk(fso, dxfPath) Then ExportActiveToDxf = dxfPath: Exit Function

    On Error Resume Next
    ok = swModel.SaveAs4(dxfPath, swSaveAsCurrentVersion, swSaveAsOptions_Silent, nErrors, nWarnings)
    If Err.Number <> 0 Then ok = False: Err.Clear
    On Error GoTo 0
    If ok Or DxfOk(fso, dxfPath) Then ExportActiveToDxf = dxfPath: Exit Function

    MsgBox "DXF export failed: " & dxfPath & vbCrLf & "Errors=" & nErrors & " Warnings=" & nWarnings, _
           vbExclamation, "RemapDxfColors"
End Function

Private Function DxfOk(ByVal fso As Object, ByVal path As String) As Boolean
    On Error Resume Next
    If fso.FileExists(path) Then If fso.GetFile(path).Size > 0 Then DxfOk = True
End Function

Private Function IsDestAci(ByVal aci As Long) As Boolean
    Dim i As Long
    For i = 0 To mapRgbN - 1
        If mapRgbAci(i) = aci Then IsDestAci = True: Exit Function
    Next i
End Function

Private Function Has420(ByVal packed As Long) As Boolean
    Dim i As Long
    For i = 0 To have420N - 1
        If have420(i) = packed Then Has420 = True: Exit Function
    Next i
End Function

' Collect existing True Color values so re-run does not undo COLOR_MAP ACI.
Private Sub ScanExisting420(ByVal dxfPath As String)
    Dim fso As Object, ts As Object, c As String, v As String
    have420N = 0: Erase have420
    ReDim have420(0 To 63)
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile(dxfPath, 1, False)
    Do While Not ts.AtEndOfStream
        c = Trim$(ts.ReadLine)
        If ts.AtEndOfStream Then Exit Do
        v = Trim$(ts.ReadLine)
        If c = "420" And IsNumeric(v) Then
            If have420N > UBound(have420) Then ReDim Preserve have420(0 To have420N * 2)
            have420(have420N) = CLng(Val(v)): have420N = have420N + 1
        End If
    Loop
    ts.Close
    If have420N > 0 Then ReDim Preserve have420(0 To have420N - 1)
End Sub

' True when lone ACI should become RGB: not mapped, no following 420,
' and (if this ACI is a COLOR_MAP destination) that RGB is not already in the file.
' Prevents second run from turning mapped ACI Red back into RGB.
Private Function ShouldRestoreAci(ByVal src As Long, ByVal nextIs420 As Boolean) As Boolean
    Dim packed As Long
    If Not RESTORE_UNMAPPED_AS_RGB Or nextIs420 Or src < 1 Or src > 9 Then Exit Function
    If LookupAci(src) >= 1 Then Exit Function
    packed = AciToPackedRgb(src)
    If packed < 0 Then Exit Function
    If IsDestAci(src) And Has420(packed) Then Exit Function
    ShouldRestoreAci = True
End Function

' COLOR_MAP hits -> 62=ACI. Lone unmapped ACI 1..9 -> 420 if RESTORE enabled.
Private Function RemapDxfFile(ByVal dxfPath As String) As Long
    Dim fso As Object, tsIn As Object, tsOut As Object
    Dim tmpPath As String, bakPath As String
    Dim codeLine As String, valLine As String, codeTrim As String, valTrim As String
    Dim peekCode As String, peekVal As String, hasPeek As Boolean, nextIs420 As Boolean
    Dim packed As Long, aci As Long, src As Long, n As Long, hit As Boolean

    nToAci = 0: nToRgb = 0
    Set fso = CreateObject("Scripting.FileSystemObject")
    If Not fso.FileExists(dxfPath) Then Err.Raise vbObjectError + 1, , "DXF not found: " & dxfPath

    ScanExisting420 dxfPath

    tmpPath = dxfPath & ".tmp": bakPath = dxfPath & ".bak"
    Set tsIn = fso.OpenTextFile(dxfPath, 1, False)
    Set tsOut = fso.OpenTextFile(tmpPath, 2, True)

    n = 0: hasPeek = False
    Do While True
        If hasPeek Then
            codeLine = peekCode: valLine = peekVal: hasPeek = False
        Else
            If tsIn.AtEndOfStream Then Exit Do
            codeLine = tsIn.ReadLine
            If tsIn.AtEndOfStream Then tsOut.WriteLine codeLine: Exit Do
            valLine = tsIn.ReadLine
        End If

        hit = False: codeTrim = Trim$(codeLine): valTrim = Trim$(valLine)

        If codeTrim = "420" And IsNumeric(valTrim) Then
            aci = LookupRgb(CLng(Val(valTrim)))
            If aci >= 1 Then WritePair tsOut, 62, CStr(aci): n = n + 1: nToAci = nToAci + 1: hit = True
        ElseIf codeTrim = "62" And IsNumeric(valTrim) Then
            src = CLng(Val(valTrim))
            If src <> 0 And src <> 256 Then
                nextIs420 = False
                If Not tsIn.AtEndOfStream Then
                    peekCode = tsIn.ReadLine
                    If Not tsIn.AtEndOfStream Then
                        peekVal = tsIn.ReadLine: hasPeek = True
                        If Trim$(peekCode) = "420" Then nextIs420 = True
                    Else
                        tsOut.WriteLine peekCode
                    End If
                End If
                aci = LookupAci(src)
                If aci >= 1 Then
                    WritePair tsOut, 62, CStr(aci): n = n + 1: nToAci = nToAci + 1: hit = True
                ElseIf ShouldRestoreAci(src, nextIs420) Then
                    packed = AciToPackedRgb(src)
                    WritePair tsOut, 420, CStr(packed): n = n + 1: nToRgb = nToRgb + 1: hit = True
                End If
            End If
        End If

        If Not hit Then tsOut.WriteLine codeLine: tsOut.WriteLine valLine
    Loop
    tsIn.Close: tsOut.Close

    If MAKE_BACKUP Then
        If fso.FileExists(bakPath) Then fso.DeleteFile bakPath, True
        fso.CopyFile dxfPath, bakPath, True
    End If
    If fso.FileExists(dxfPath) Then fso.DeleteFile dxfPath, True
    fso.MoveFile tmpPath, dxfPath
    RemapDxfFile = n
End Function