I get an error "Error in wb$workbook$sheets[[i]] : subscript out of bounds" in the " wb = openxlsx::loadWorkbook(filepath)" line in the following block of code.
# If file exists, open it; if it does not exist, create it
if (file.exists(filepath)) {
wb = openxlsx::loadWorkbook(filepath)
# If sheet already exists, delete it
if (sheetname %in% openxlsx::getSheetNames(filepath)) {
openxlsx::removeWorksheet(wb, sheet = sheetname)
}
} else {
wb = openxlsx::createWorkbook()
}
# Write out the data to the worksheet
openxlsx::addWorksheet(wb, sheetname)
openxlsx::writeData(wb, sheet = sheetname, data, colNames = TRUE)
# Save out updated Excel file
openxlsx::saveWorkbook(wb, filepath, overwrite = TRUE)
Expected Behavior
Overwrite the sheet
Actual Behavior
Report an error "Error in wb$workbook$sheets[[i]] : subscript out of bounds." The code works If I manually open the file after writing a sheet and then save it and close it.
I get an error "Error in wb$workbook$sheets[[i]] : subscript out of bounds" in the " wb = openxlsx::loadWorkbook(filepath)" line in the following block of code.
Expected Behavior
Overwrite the sheet
Actual Behavior
Report an error "Error in wb$workbook$sheets[[i]] : subscript out of bounds." The code works If I manually open the file after writing a sheet and then save it and close it.
Steps to Reproduce the Problem
Have an existing Excel file
Overwrite existing sheet.
sessionInfo()