How can I ensure that the current active cell is valid and stored when the user wants to close the document?

You should process CDocument::CanCloseFrame( ) in the following way:

BOOL CGridSampleDoc::CanCloseFrame(CFrameWnd* pFrame)
{
   // Ensure that views can be deactivated
   CView* pView = pFrame->GetActiveView();
   if (pView && pView->SendMessage(WM_GX_CANACTIVATE, 0, 0))
      return FALSE;
   // Is it a grid?
   CGXGridCore* pGrid = NULL;
   if (pView->IsKindOf(RUNTIME_CLASS(CGXGridView)))
      pGrid = (CGXGridCore*) ((CGXGridView*) pView);
   else if (pView->IsKindOf(RUNTIME_CLASS(CGXGridHandleView)))
      pGrid = ((CGXGridHandleView*) pView)->GetGrid();
   if (pGrid)
   {
      // Ensure that the current cell can be stored
      if (!pGrid->TransferCurrentCell(TRUE, GX_UPDATENOW, FALSE))
         // grid state is invalid, don't close the frame
         return FALSE;
   }
   // Now, I can close the view
   return CDocument::CanCloseFrame(pFrame);
}

You should also transfer the current cell data to the grid before saving the document.

Example:

BOOL CDbfBrowserDoc::OnSaveDocument(LPCTSTR pszPathName)
{
// TRACE1("CDocument: OnSaveDocument(%s)\n", pszPathName);
   // Ensure that each views current cell is stored
   CGXGridHint hint(gxHintTransferCurrentCell);
   hint.lParam = TRUE;
   UpdateAllViews(NULL, 0, &hint);
   // Now, I can save the document
   if (!CDocument::OnSaveDocument(pszPathName))
      return FALSE;
   SetModifiedFlag(FALSE);
   return TRUE;
}