-
Hi, Thank you very much for the great package! I am currently trying to implement some automations and ran into a an issue when using SWITCH in a formula within a data table. Here is a minimal example:
When opening the file in Excel, I get #NAME? errors. This is due to an @ that is added at the beginning of the SWITCH statement. That is, the formula in Excel is I am using R 4.4.0 on Windows 11 with openxlsx2 version 1.11.0.9000. Best, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @jhorzek , thank you for your kind words! The error is related to the following: As can be seen the list of Excel functions, To use this function you have to add the prefix I haven't really researched cm-functions, it is possible to write them with library(openxlsx2)
wb <- wb_workbook()
example_data <-
data.frame(
sales_price = c(20, 30, 40),
COGS = c(5, 11, 13),
sales_quantity = c(1, 2, 3)
)
## base R method
example_data$switch1 <- "=_xlfn.SWITCH(daily_sales[[#This Row],[sales_price]], 20, 1, 0)"
example_data$switch2 <- "=IF(daily_sales[[#This Row],[sales_price]] > 0, _xlfn.SWITCH(daily_sales[[#This Row],[sales_price]], 20, 1, 0), NA())"
class(example_data$switch1) <- c(class(example_data$switch1), "array_formula")
class(example_data$switch2) <- c(class(example_data$switch2), "array_formula")
wb$
add_worksheet("Daily Sales")$
add_data_table(
x = example_data,
table_style = "TableStyleMedium2",
table_name = "daily_sales",
)
if (interactive()) wb$open() PS: I move this question to discussion, because it is working as expected. The only way to avoid this, would be to always try to keep up with the Excel formula list and parse the formulas ... something I do not really desire. |
Beta Was this translation helpful? Give feedback.
Hi @jhorzek , thank you for your kind words!
The error is related to the following:
As can be seen the list of Excel functions,
SWITCH()
is a modern Excel formula (the label MS365 gives the hint)To use this function you have to add the prefix
_xlfn.
(see here). There is another nasty thing:The function is a cell metadata function - basically an array function with a special tag to hide that it is an array function. You can use the code below, which will make the function work as expected, but will show its array roots.
I haven't really researched cm-functions, it is possible to write them with
wb_add_formula(cm = TRUE)
but they print a warning since their initial implementation and unf…