RDCOMClient : read and write Excel, and call VBA macro in R

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.



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.

1
2
3
4
5
6
7
8
9
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
cs


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().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#=========================================================================#
# 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() 
    
cs


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. \(\blacksquare\)

Related Posts




4 comments:

  1. Hi, when I use:

    *install.packages("RDCOMClient",repos="http://www.omegahat.net/R")*

    this shows:

    *Warning in install.packages :
    unable to access index for repository http://www.omegahat.net/R/bin/windows/contrib/4.1:
    cannot open URL 'http://www.omegahat.net/R/bin/windows/contrib/4.1/PACKAGES'
    Package which is only available in source form, and may need compilation of
    C/C++/Fortran: ‘RDCOMClient’
    These will not be installed*

    Could you please help me
    Thank you
    Gabriela

    ReplyDelete
    Replies
    1. Thank you for visiting my blog.

      Try the second installation. (you need to install devtools library in advance by [clicking Tools -> Install Packages]in R Stduio)

      devtools::install_github("omegahat/RDCOMClient")

      It will works.

      Delete
  2. Hello Sang-Heon Lee,

    Which parts would I modify to use my own excel file? Can I run multiple macros through this method?

    Thank you,
    Jacob

    ReplyDelete
    Replies
    1. Hi, you need to modify the following commands for your problem.

      1) working directory and file name
      setwd("D:/SHLEE/blog/excel_com")
      fn <- "sample_excel.xlsm"

      2) sheet, range, and macro
      sheet <- "Sheet1"
      range_in <- "C3:C12"
      range_out <- "D3:D12"
      macro_name <- "macro1"

      3) input data
      data_in <- 1:10

      I hope this helps.

      Delete