3

I am trying to use the Excel advanced filter through PowerShell, but I am not having any luck. I can use an autofilter successfully by running the following code:

$rangetofilter = $worksheet2.usedrange.select
$excel.selection.autofilter(2, "TestFilter")

However, I don't understand how to properly convert the syntax given in Range.AdvancedFilter Method to something that PowerShell will accept. For example, I've tried

$excel.selection.AdvancedFilter("xlFilterInPlace", "", "", "TRUE")

But I get the following error:

Exception calling "AdvancedFilter" with "4" argument(s): "AdvancedFilter method of
Range class failed"
At line:1 char:32
   + $excel.selection.AdvancedFilter <<<< ("xlFilterInPlace","","","TRUE")
   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
   + FullyQualifiedErrorId : ComMethodTargetInvocation

So is there a way to run an Excel advanced filter through PowerShell?

I found this: Delete duplicate rows in excel using advanced filter, but it is not working either...

4

1 回答 1

6

的参数都不AdvancedFilter()是字符串。

Object AdvancedFilter(
    XlFilterAction Action,
    Object CriteriaRange,
    Object CopyToRange,
    Object Unique
)

第一个是枚举。在 VBA 中,您可以直接使用它们,因为它们是隐式全局的。在 Powershell 中并非如此,您必须通过它们的完全限定名称显式引用它们:

$xlFilterInPlace = [Microsoft.Office.Interop.Excel.XlFilterAction]::xlFilterInPlace

其他三个参数的类型为Object,这意味着它们属于VariantCOM 类型。但是,#2 和#3 应该是Range对象,如果你传入其他东西,所有的赌注都会被取消。

它们也被标记为可选。应该没有值的可选参数由.NET COM 互操作中Missing类型表示。同样,在 Powershell 中,您必须明确引用它:

$missing = [Type]::Missing

参数 #4 应该是一个布尔值,所以只需传递一个 Powershell 布尔常量(或者,因为这个参数也是可选的,所以$missing)。

$excel.Selection.AdvancedFilter($xlFilterInPlace, $missing, $missing, $TRUE)
于 2013-05-06T04:43:08.187 回答