简体   繁体   English

如果它与 Excel 的 Office 脚本中的变量匹配,则尝试删除范围内的日期

[英]Trying to delete the date within a range if it matches a variable in Office scripts for Excel

I have a column with dates stored that need to be cleared if they match a variable.我有一个存储日期的列,如果它们与变量匹配则需要清除。

I've tried a ton of different ways, but this is my most recent attempt:我尝试了很多不同的方法,但这是我最近的尝试:

let dateRange = selectedTable
.getColumnByName("Date")
.getRangeBetweenHeaderAndTotal()
.getTexts();

let date: string = "12/2/2022"

console.log(dateRange);

dateRange.forEach(dates => {
  if (dates === date){
    ExcelScript.ClearApplyTo.contents
  }
})

This one won't work as 'dates' is an array and can't be compared to the 'date' variable as far as I can tell.这个不起作用,因为“日期”是一个数组,据我所知无法与“日期”变量进行比较。

I think there are two issues you might be running into here:我认为您可能会在这里遇到两个问题:

First: getTexts() returns a 2D array to preserve the row/column structure of the grid.首先: getTexts()返回一个二维数组以保留网格的行/列结构。 So even though dateRange is a column, it's still a 2D array - something like [['value1'], ['value2'], ...] .因此,即使dateRange是一列,它仍然是一个二维数组 - 类似于[['value1'], ['value2'], ...] You can get a single cell with the expression dateRange[rowIndex][0] .您可以使用表达式dateRange[rowIndex][0]获取单个单元格。

Second: ExcelScript.ClearApplyTo.contents is simply an enum member and does not do anything on its own.第二: ExcelScript.ClearApplyTo.contents只是一个枚举成员,它自己不做任何事情。 To clear the contents of a specific cell/range, you need to call the clear() method on the corresponding Range object.要清除特定单元格/区域的内容,您需要在相应的Range object 上调用clear()方法。

Putting this together, you get the following script (assuming you've defined selectedTable elsewhere):将它们放在一起,您将获得以下脚本(假设您已在别处定义selectedTable ):

  let dateRange = selectedTable
    .getColumnByName("Date")
    .getRangeBetweenHeaderAndTotal();
  let texts = dateRange.getTexts();
  let date: string = "12/2/2022"

  texts.forEach((text, row) => {
    if (text[0] === date) {
      dateRange.getCell(row, 0).clear();
    }
  })

Additionally, as pointed out in the comments, you should be careful about date formatting.此外,正如评论中所指出的,您应该注意日期格式。 Since you're comparing strings, this script will fail to clear cells that contain 12/02/2022 , December 2, 2022 , etc. even though the underlying date is the same.由于您正在比较字符串,因此此脚本将无法清除包含12/02/2022December 2, 2022等的单元格,即使基础日期相同也是如此。

Hopefully that helps!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM