Refer to result of cell above current cell?
You can use something like this. (I have added extra steps to demonstrate practical usage.)
Selectable code
x = 3
y = x + 2;
Clear[x, y, z]
SelectionMove[EvaluationNotebook[], Previous, Cell, 3];
z = ToExpression@First@NotebookRead[EvaluationNotebook[]];
y + z
Addendum
Further to xzczd's comment, you can also use a cell tag :-
Version 9 offers a couple of new ways to access cells that are useful to meet the needs of this question.
The first way involves the use of the Cells and EvaluationCell functions. They can be used in the present context like this:
previousCell[] :=
Cells @ EvaluationNotebook[] /. {___, prev_, EvaluationCell[], ___} :>
ToExpression @ First @ NotebookRead @ prev
Here, we retrieve all cells from the evaluation notebook and use pattern matching to find the cell prior to the currently evaluating cell. Having recovered that cell object, we extract its box representation and convert it to an expression. Proper error- and boundary-checking are left as exercises for the reader. This method's use of pattern-matching can be helpful if more elaborate conditions are needed to identify the sought cell.
A second approach is to use the undocumented function Experimental`ToCellIndex
and its companion Experimental`FromCellIndex
:
previousCell2[] :=
ToExpression @ First @ NotebookRead @
Experimental`FromCellIndex[Experimental`ToCellIndex @ EvaluationCell[] - 1]
The index of the evaluating cell is recovered using FromCellIndex
, decremented, and then converted back to a cell object using ToCellIndex
. The cell contents are then extracted using the same method as in previousCell
. This method is more direct in that it operates upon cell indices, but lacks the flexibity of the earlier pattern-matching approach. Also, these experimental functions simply use Cells
internally, so they do not offer any speed-up over direct use of that function.
Edit
As @Jacob Akkerboom notes in the comments, the Experimental
package has more cell helper functions. Of particular interest is Experimental`PreviousCell[]
which, by default, returns the cell immediately prior to the evaluation cell, i.e. exactly what is requested by this question (how did I miss that in my initial response?). The full signature of that function is essentially equivalent to:
Experimental`PreviousCell[cell_CellObject:EvaluationCell[], style_:All, n_Integer:1]
cell
is the reference cell. style
names the style of cells to consider when counting, with All
meaning all styles. n
is how many cells to count backwards to locate the target cell. There is also Experimental`NextCell[]
which operates in similar fashion but in the forward direction.
The implementations of Experimental`NextCell
and Experimental`PreviousCell
(and the other experimental cell functions) are all based upon the Cells
function.
Just for completeness, PreviousCell
and NextCell
were promoted to System`
functions in version M10. For example: