Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Let's say I select 2 different cells and then attempt to replace their content using NotebookWrite inside a button. How might I replace each cell's content individually instead of the current functionality I am getting.

Button["Write", NotebookWrite[EvaluationNotebook[], "Write"]]
Dynamic[Refresh[NotebookRead[SelectedNotebook[]],UpdateInterval -> 1]]

enter image description here

When I click on the Write button, only the last selected Cell gets replaced.

enter image description here

Is there a safe technique to replace each cell with unique content?

share|improve this question

1 Answer 1

up vote 10 down vote accepted

This is very straightforward in v9 using Cells and CellObject. Let's start with a notebook with a disjoint selection of the type you're describing:

nb = NotebookPut[
  Notebook[{
    Cell["a", CellTags -> "x"],
    Cell["b"], 
    Cell["c", CellTags -> "x"]}]];
NotebookFind[nb, "x", All, CellTags]

Now, we can get CellObjects for the selected cells by using Cells.

cells = Cells[NotebookSelection[nb]]

NotebookWrite allows you to overwrite any given CellObject.

NotebookWrite[First[cells], Cell["d"]]
NotebookWrite[Last[cells], Cell["e"]]

And this NotebookWrite operation can be done regardless of where the selection is at the time. If you want to manipulate a notebook without having to fiddle with selections, CellObject is a very powerful tool and worth further exploration.

share|improve this answer
    
Thank you again! –  Liam William Aug 8 at 17:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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