使用ListObject.Add创build表格样式时出错

我试图创build一个自定义表(就像在Excel中单击“格式为表格”),从CSV中使用PowerShell和Excel ComObject

这是我的代码…

$Excel = New-Object -ComObject excel.application $Excel.visible = $true $Excel.sheetsInNewWorkbook = $csvFiles.Count $workbooks = $excel.Workbooks.Add() $worksheets = $workbooks.worksheets $CSVFullPath = C:\temp.csv $worksheet = $worksheets.Item(1) $worksheet.Name = "Temp" $TxtConnector = ("TEXT;" + $CSVFullPath) $CellRef = $worksheet.Range("A1") $Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef) $worksheet.QueryTables.item($Connector.name).TextFileCommaDelimiter = $True $worksheet.QueryTables.item($Connector.name).TextFileParseType = 1 $worksheet.QueryTables.item($Connector.name).Refresh() $worksheet.UsedRange.EntireColumn.AutoFit() ## So Far So good - CSV Imported ## ## My Problem Starts here... ## $listObject = $worksheet.ListObjects.Add([Microsoft.Office.Interop.Excel.XlListObjectSourceType]::xlSrcRange, $worksheet.UsedRange, $null),[Microsoft.Office.Interop.Excel.XlYesNoGuess]::xlYes,$null) ## Then I Received the following error: ## Exception calling "Add" with "5" argument(s): "A table cannot overlap a range that contains a PivotTable report, query results, protected cells or another table." At line:1 char:41 + $ListObject = $WorkSheet.ListObjects.Add <<<< ([Microsoft.Office.Interop.Excel.XlListObjectSourceType]::xlSrcRange,$R ange,$null,[Microsoft.Office.Interop.Excel.XlYesNoGuess]::xlYes,$null) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ComMethodTargetInvocation 

我已经有一段时间了,没有find解决办法。

根据您的代码,您不能将基础QueryTable仍然适当地添加到WorksheetListObject 。 如果您尝试在正常的Excel(非COM)中执行此操作,将会出现如下错误:

在这里输入图像说明

如果您在其中键入“ Yes并在其工作时录制一个macros,则Excel将删除QueryTable并添加ListObject 。 删除QueryTable不会影响底层数据。

在VBA世界里,你的代码看起来像这样:

 Sub DeleteQueryTableAndAddListObject() Dim sht As Worksheet Set sht = ActiveSheet ''code up here to create a QueryTable Dim i As Integer For i = sht.QueryTables.Count To 1 Step -1 sht.QueryTables(i).Delete Next i sht.ListObjects.Add xlSrcRange, sht.UsedRange, , xlYes End Sub 

采取PowerShell刺(不是我的母语)你应该能够做到:

 $worksheet.QueryTables.item($Connector.name).Delete() 

或者可能:

 $Connector.Delete() 

因为$Connector似乎是对QueryTable对象的有效引用。