views:

136

answers:

3

I've got some Excel spreadsheets that are hitting the database pretty hard (100+ queries against the general ledger table... yikes!). Refreshing just the sheet I'm on (SHIFT+F9) is helpful in some spreadsheets, but I wanted a way to refresh just the selected cells. I'm came up with the following code, placed in the ThisWorkbook object:

Dim currentSelection As String

Private Sub Workbook_Open()
    Application.OnKey "+^{F9}", "ThisWorkbook.RecalculateSelection"
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    currentSelection = Target.Address
End Sub

Private Sub RecalculateSelection()
    Range(currentSelection).Calculate
End Sub

If possible, I'd like to make this more portable, such as storing it in an XLA file and loading it as an Excel addin. Is this possible with the method I'm using? Is there a better way to achieve this?

+2  A: 

If you just want to recalculate the currently selected cells, ignoring cells that are dependent on them you can use my RangeCalc addin, downloadable from http://www.decisionmodels.com/downloads.htm

Charles Williams
Looks like your addin does exactly what I'm after. I wish I could accept more than one answer. To be fair, I had to accept Chris Spicer's answer because I went with his solution.
Scott
Thank you: the RangeCalc addin also handles automagically some of the quirks of Range.Calculate: seehttp://www.decisionmodels.com/calcsecretsg.htm
Charles Williams
+1  A: 

You should be able to use the following:

Public Sub RecalculateSelection()
    Dim rng As Range
    Set rng = Application.Selection
    rng.Calculate
End Sub

You should place some error handling around the 'Set rng' line, as the user may not have selected a range (e.g. they may have selected a chart).

By using the application object you don't need to capture the Workbook_SheetSelectionChange event.

Chris Spicer
Perfect! I suspected there was an easier way, but the world of Excel VBA is still very new to me.
Scott
+1  A: 

if your using the method from the accepted answer above you should first check that...

If Not Selection Is Nothing Then
  If TypeName(Application.Selection) = "Range" Then 
  Dim Rng As Range 
  Set Rng = Application.Selection 
  Rng.Calculate 
 End If 
End If 

Also you might like to add it to the sheet and sheetname context menus. The name of the two commandbars that you need to do that are... "Cell" and "Ply"

Anonymous Type