title: catia vba Do Until .saved and DoEvents, how to regain control of CATIA?
body: <p>This code allows me to quickly close and, if necessary, save documents with a keyboard shortcut.</p>
  
  <pre><code>Sub CATMain()
  
  Dim doc As Document
  Set doc = CATIA.ActiveDocument
  
  Dim MsgBoxRes As String
  
  If doc.Saved Then
      doc.Close
  Else
      MsgBoxRes = MsgBox("Document has changes, save &amp; close?", vbOKCancel)
      If MsgBoxRes = "1" Then
          If Left(doc.FullName, 1) &lt;&gt; "Y" Then
              CATIA.StartCommand "save as"
              doc.Close
          Else
              doc.Save
              doc.Close
          End If
      Else
          Exit Sub
      End If
  End If
  
  End Sub
  </code></pre>
  
  <p>When I use the Save As dialog box and save my document, the code <strong>does not always</strong> properly resume or it skips the next command(s), I'm not sure what the case is here. (Practically this means my document won't close)<br>
  Therefore I tried inserting a sleep time, which didn't change anything so I also tried adding a Do Until loop with a DoEvents method and this completely broke the macro.
  See here my failed attempt at fixing the problem:</p>
  
  <pre><code>Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
  
  Sub CATMain()
  
  Dim doc As Document
  Set doc = CATIA.ActiveDocument
  
  Dim MsgBoxRes As String
  
  If doc.Saved Then
      doc.Close
  Else
      MsgBoxRes = MsgBox("Document has changes, save &amp; close?", vbOKCancel)
      If MsgBoxRes = "1" Then
          If Left(doc.FullName, 1) &lt;&gt; "Y" Then
              CATIA.StartCommand "save as"
              DoEvents
              Do Until doc.Saved
                  DoEvents
                  If doc.Saved Then doc.Close
                  DoEvents
                  Sleep 100
              Loop
          Else
              doc.Save
              doc.Close
          End If
      Else
          Exit Sub
      End If
  End If
  
  End Sub
  </code></pre>
  
  <p>My problem now becomes much worse; while in the Do loop VB won't allow CATIA or the user to do anything and I need to use <kbd>Ctrl</kbd>+<kbd>Break</kbd> to get out of the loop.  </p>
  
  <p>Is there a way to make this code work while still using catia.startcommand "save as" ?  </p>
  
  <p>I know it should be possible to accomplish the same thing by making my own dialog box where the user browses to and selects the correct save location, but if possible I'd much rather just use the catia.startcommand.</p>