This post gives an short introduction to the RDCOMClient R package, which provides a variety of functionalities. Our focus is on reading from and writing to Excel, and call VBA macro function in R.
Using RDCOMClient R package, we can read from and write to Excel spreadsheet, furthermore, call VBA macro function in R. Of course this VBA is running in Excel not R. We can get results which are returned from VBA macro which was developed earlier.
This feature is very useful when this macro calls DLL, which is hard to be called in R for some reason. At last, we can get the same effect of calling DLL in R indirectly by using RDCOMClient package.
Unlike other packages, RDCOMClient is installed using the following command.
Excel Example with VBA macro
The following figure shows the operation of macro1() function by clicking [run macro1] rectangular button. macro1() returns squares of input variables simply.
The VBA code of macro1() is as follows.
For i = 1 To 10
Worksheets(“Sheet1”).Range(“D2”).Offset(i, 0).Value _
= WorksheetFunction.Power( _
Worksheets(“Sheet1”).Range(“C2”).Offset(i, 0).Value, 2)
The following R code implements three operations:
- Write input array to Excel
- Run macro1()
- Read output array from Excel
R code is simple and self-contained so that you can easily understand it. For convenience, we make two functions : f_read_vector() and f_write_vector().
The following console shows two outputs for each input array. This output is calculated in Excel by using VBA function not by using R.
In fact, running the above R code results in the following calculation outputs of Excel spreadsheet. R is only to read these results.
This post deals with a simple exercise (reading and writing) of RDCOMClient R package. In particular, when VBA macro function calls DLL, we can use this DLL indirectly by calling not DLL but its wrapper VBA macro. This is useful when you have difficulties in calling DLL directly in R for some reason. \(\blacksquare\)