Search code examples
rexcelxlconnectvba

xlconnect R package disables calculations in an Excel template


I'm trying to write raw data from R in an Excel template, then run a little VBA macro to turn the raw data into something nice and presentable. I use XLConnect. The problem is that XLConnect seems to disable the calculations in the Excel worksheet.

Here's my R code for writing my dataframe to Excel:

VaR.dataframe = structure(list(names = c("VaR.montecarlo", "TVaR.montecarlo", "VaR.historic.1yr", "VaR.historic.2yr", "VaR.historic.3yr", "VaR.gaussian"), X95. = c(0.0363375421892311, 0.0507403479325009, 0.0402675195649073, 0.0400483852784169, 0.0357565527744698, 0.038409381028186), X97.5. = c(0.0473956950987274, 0.0598796459552848, 0.0528350062512669, 0.0483427549702983, 0.0432047576422228, 0.0488252950503447), X99. = c(0.0589594848085542, 0.0714812674589506, 0.06597791329211, 0.0596859927016254, 0.0544507369487263, 0.0609360460943547)), .Names = c("names", "X95.", "X97.5.", "X99."), class = "data.frame", row.names = c(NA, -6L))    
template_filename = "C:\\Temp\\my_template.xlsm"
writeWorksheetToFile(file = template_filename, data = VaR.dataframe, sheet = "VaR")

This goes into a raw sheet called VaR which I wouldn't show to clients. The thing I would show to clients looks more like this:

enter image description here

All the numbers in the table are VLOOKUP formulas into the raw VaR sheet. The final step is to run a little VBA macro which will copy-paste-special-values over the formulae, and delete the horrid-looking orange rows and columns.

The problem is after the R script has updated my Excel template, the formulas don't work. Even if I open the workbook and press F9 to calculate, they are all #N/A. This will stay true until I do a forced calculate by going Ctrl-Alt-F9.

My first instinct was to force the Ctrl-Alt-F9 key combination within my VBA macro:

Call Application.SendKeys("^%{F9}")

But this doesn't seem to work, either.

Does anyone know how to force the calculation in the macro? Or suggest an Excel-writing R package which won't corrupt my spreadsheet?


Solution

  • For Ctrl/Alt/F9 try Application.CalculateFull