Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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"

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top