2

Is there a way to preserve the macros in .xlsm files when processing data with R?

I was using the "read_excel" function from "readxl" package to read xlsm data into R, process it, and then export it back to Excel using the "write.xlsx" function in the "openxlsx" package.

However, the write.xlsx function does not allow the output to be an .xlsm file.

I tried an alternative way, using the loadWorkbook and saveWorkbook functions from the "xlsx" package, as suggested in Populating Excel Macro-enabled cells from R/outside environment.

However, this time, my data processing code does not work any more, producing an error, "Error in apply(df, 1, setfunction) : dim(X) must have a positive length".

My code works fine when using the openxlsx and readxl packages, except that all macros were lost in the output.

Is there a way to preserve the macros in .xlsm files when processing data with R?

    df<-loadWorkbook("data.xlsm") # originally was df<read_excel("data.xlsm")

    setfunction <- function (x) {
                set1 <- strsplit(x[[2]], split=",")
                set2 <- strsplit(x[[3]], split=",")
                trimset1 <- sapply(set1[[1]], str_trim)
                trimset2 <- sapply(set2[[1]], str_trim)
                set3 <- setdiff(trimset1, trimset2)
                newset3 <- paste(set3, collapse = ', ')
    }

    df$newcol <- apply(df, 1, setfunction)

    saveWorkbook("data2.xlsm") # originally was write.xlsx(df, file = data2.xlsx")
Susan
  • 203
  • 2
  • 6
  • You might want to try the following link: https://stackoverflow.com/questions/31493130/populating-excel-macro-enabled-cells-from-r-outside-environment – DTYK Jul 17 '18 at 08:28
  • yes, tried, the link you gave is the same link I put in the question. R returns the error "Error in apply(df, 1, setfunction) : dim(X) must have a positive length". – Susan Jul 21 '18 at 05:05

0 Answers0