2
$\begingroup$

I have modified a Notebook programmatically like this. The notebook may have been loaded or not before the function is called:

ImportStylesheet[fn_] :=
  Module[{nbk}
         , nbk = NotebookOpen[fn];
          If[nbk == $Failed
             ,Print["ImportStylesheet: Wrong Filename"]; 
              Throw["Wrong filename!"]
             ];
          SetOptions[EvaluationNotebook[]
                    ,Sequence[Options[nbk
                                      , StyleDefinitions
                                      ]
                              ]
                    ];
          NotebookSave[nbk, fn];  (* might have been open before *)
          NotebookClose[nbk];     (* closes it without asking *)
         ];

Since the notebook from which I import the privte Stylesheet, already may have been open NotebookOpen in my function, I decide that it is better to automatically save it to prevent loosing edits applied to it which have not been saved. Therefore I added NotebookSave[nbk, fn]; before NotebookClose[nbk];.

But I get an error message "Why the Beep?" telling me:

Part of the path ...(my nb's  full path)... does not exist. Unable to
save the file ....

Why this message? FileNames[fn] shows me that the notebook with filename fn exists and in case it was not an open Notebook before it is opened during the operation of my function ImportStylsheet. Any Idea how to cope with it?

$\endgroup$
1
$\begingroup$

The point is to use the form of NotebookSave[nbk] without a second parameter describing the file location:

ImportStylesheet::usage =
"ImportStylesheet[fn]\nImport the private Stylesheet of the Nb designated by fn. If this Nb was open before, it will be stored automatically at the end of this function to prevent loosing edits by closing the nb.";
ImportStylesheet[fn_] :=
  Module[{nbk}
         ,nbk = NotebookOpen[fn];
          If[nbk == $Failed
             ,Print["ImportStylesheet: Wrong Filename: ", fn]; 
              Throw["Wrong filename!"]; (* ====THROW===> *)
             ];
          SetOptions[EvaluationNotebook[]
                    ,Sequence[Options[nbk
                                     ,StyleDefinitions
                                     ]
                             ]
                    ];
          NotebookSave[nbk]; (* the nb might have been open before *)
          NotebookClose[nbk];(* this would close it without asking *)
         ];                  (* ImportStylesheet *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Your problem may have had to do with not using ExpandFileName@fn. For example on Unix NotebookSave[EvaluationNotebook[], "~/Desktop/test.nb"] pops up the message window you saw. Does that fix it? $\endgroup$ – b3m2a1 Nov 28 '16 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.