名称与_FilterDatabase冲突

时间:2013-02-01 10:37:50

标签: excel powershell autofilter

我尝试在同一个文件上第二次运行Powershell脚本后,出现“名称冲突”对话框。我知道这个错误与我自动过滤文件有关。如果我从不使用自动调整,则不会显示该对话框。我究竟做错了什么?这是代码:

$excel = new-object -comobject excel.application
$excel.DisplayAlerts = $false

$workbook = $excel.Workbooks.open("testtabelle1.xlsx")
Trap {"Worksheet problems..."} $workbook.Worksheets.Item(1) | Out-Null

$from = ">0"
$to = "<2"

$workbook.ActiveSheet.Range("D:D").AutoFilter(1, $from, 1, $to) > $null

#Reset Selection and close file
#$workbook.ActiveSheet.Range("A1").Select() | Out-Null
$workbook.Save()
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

3 个答案:

答案 0 :(得分:4)

您必须删除名称“_FilterDatabase”,因为此名称只允许使用一次。

Names对象是hastable。因此,您需要删除这样的键:

$workbook.Names.Item("_FilterDatabase").Delete()

答案 1 :(得分:0)

$workbook.Names.Item("_FilterDatabase").Delete()之后执行类似的操作可能也很有用:

$Items_FD = $workbook.Names | ?{ $_.Name -match "_FilterDatabase" }
$Items_FD | %{
  try{
    $_.Delete() | Out-Null
  }
  catch{}
}

答案 2 :(得分:0)

Sub IdentifyNames()

Dim defName As Name

With ThisWorkbook 'Entire workbook
  For Each defName In .Names
  If Right(defName.Name, 14) = "FilterDatabase" Then defName.delete
  'Debug.Print defName.Name
  Next
End With

End Sub

注释部分列出了已定义的名称