Close Navigation
Learn more about IBKR accounts
RDCOMClient: Read and Write Excel, and Call VBA Macro in R

RDCOMClient: Read and Write Excel, and Call VBA Macro in R

Posted October 2, 2023
Sang-Heon Lee
SHLee AI Financial Model

This post gives a 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.

Introduction

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.

Installing

Unlike other packages, RDCOMClient is installed using the following command. It seems that the second installation is working and the first is not.

install.packages(“RDCOMClient”,repos=”http://www.omegahat.net/R”)
or
devtools::install_github(“omegahat/RDCOMClient”)

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.

Sub macro1()
 
    For i = 1 To 10
        Worksheets("Sheet1").Range("D2").Offset(i, 0).Value _
        = WorksheetFunction.Power( _
            Worksheets("Sheet1").Range("C2").Offset(i, 0).Value, 2)
    Next
    
End Sub

R code

The following R code implements three operations:

  1. Write input array to Excel
  2. Run macro1()
  3. 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().

#=========================================================================#
# Financial Econometrics & Derivatives, ML/DL using R, Python, Tensorflow  
# by Sang-Heon Lee 
#
# https://shleeai.blogspot.com
#-------------------------------------------------------------------------#
# Read and Write Excel in R, also call VBA macro in R using RDCOMClient
#
# Install package (Not available on CRAN at 12 June 2019)
# install.packages("RDCOMClient", repos = "http://www.omegahat.net/R")
#=========================================================================#
 
library(RDCOMClient)
 
graphics.off()  # clear all graphs
rm(list = ls()) # remove all files from your workspace
 
#===============================================================================
# functions using RDCOMClient
#===============================================================================
 
f_read_vector <- function(xlWbk1, sheet1, range1){
    
    sheet <- xlWbk1$Worksheets(sheet1)
    range <- sheet$Range(range1)
    data  <- do.call("cbind",range[["Value"]])
    data  <- matrix(unlist(data), dim(data)[1], dim(data)[2])
    return(data)
}
 
f_write_vector <- function(xlWbk1, sheet1, range1, data1) {
    
    sheet <- xlWbk1$Worksheets(sheet1)
    range <- sheet$Range(range1)
    range[["Value"]] <- asCOMArray(data1)
}
 
#===========================================================
# MAIN
#===========================================================
    
    # set working directory
    setwd("D:/SHLEE/blog/excel_com")
    
    # Create Excel Application
    xlApp <- COMCreate("Excel.Application")
    
    # Open the Macro Excel book
    fn <- "sample_excel.xlsm"
    xlWbk <- xlApp$Workbooks()$Open(paste0(getwd(),"/",fn))
    
    # use TRUE for Excel Spreadsheet to be visible
    xlApp[['Visible']] <- FALSE 
 
#===========================================================
# Communicate between R and Excel
#===========================================================
 
    # Arguments for Excel Spreadsheet and VBA macro
    sheet      <- "Sheet1"
    range_in   <- "C3:C12"
    range_out  <- "D3:D12"
    macro_name <- "macro1"
    
    #----------------
    # Example 1
    #----------------
    
    # 1) write input values from R to Excel
    data_in <- 1:10
    f_write_vector(xlWbk, sheet, range_in, data_in) 
    
    # 2) run Excel macro
    xlApp$Run(macro_name)
    
    # 3) read output values from R to Excel
    data_out <- f_read_vector(xlWbk, sheet, range_out)
 
    print(cbind(data_in, data_out))
    
    #----------------
    # Example 2
    #----------------
    
    data_in <- rnorm(10)
    f_write_vector(xlWbk, sheet, range_in, data_in) 
    xlApp$Run(macro_name)
    data_out <- f_read_vector(xlWbk, sheet, range_out)
    print(cbind(data_in, data_out))
    
#===========================================================
# save and quit
#===========================================================
xlWbk$close(TRUE); xlApp$Quit() 

Results

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.

Conclusion

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. 

Originally posted on SHLee AI Financial Model blog.

Join The Conversation

If you have a general question, it may already be covered in our FAQs. If you have an account-specific question or concern, please reach out to Client Services.

Leave a Reply

Your email address will not be published. Required fields are marked *

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from SHLee AI Financial Model and is being posted with its permission. The views expressed in this material are solely those of the author and/or SHLee AI Financial Model and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.