设置UsedRange值时的Excel Interop 0x800A03EC

2cmtqfgy  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(103)

Unmerging excel rows, and duplicate data c#获取部分代码
我正在将Excel工作表转换为CSV。有些单元格被合并了,所以我想取消合并并复制这些数据,而不是丢失它。

$Script:comExcelWB = $Script:comExcelApp.Workbooks.Open($TargetXlsxPath.FullName)
foreach ($Script:comExcelWS in $Script:comExcelWB.Worksheets) {
    if ($Script:comExcelWS.Visible) {
        $Script:comExcelWS.Select()
        foreach ($Script:comExcelRNG in $Script:comExcelWS.UsedRange) {
            if ($Script:comExcelRNG.MergeCells) {
                $Script:comExcelMA = $Script:comExcelRNG.MergeArea
                $Script:comExcelRNG.UnMerge()
                $Script:comExcelMA.Value = $Script:comExcelRNG.Value # Throws 0x800A03EC here
            }
        }
        $Script:comExcelWB.SaveAs("$($WSDestination.FullName)\$($Script:comExcelWS.Name).csv",
            [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV, [Microsoft.Office.Interop.Excel.XlSaveAsAccessMode]::xlNoChange)
    }
}

我错过了什么?

  • MergeArea声明属性为Range
  • 范围属性显示了设置值的两种可能方法:
  • 值[对象]:参数是可选的,默认值似乎是我想要的。崩溃如上所述。
  • Value 2:备注说明除了Current/Date类型外,它没有什么不同。在任何数据类型上如上所述崩溃。
izkcnapc

izkcnapc1#

或许,这一切都与空值有关吧?

  • 如果是NULL,检查范围,如果不是,继续设置
  • 使用Value2并转换为String(以避免Double-> String转换错误)
$Script:comExcelWB = $Script:comExcelApp.Workbooks.Open($TargetXlsxPath.FullName)
foreach ($Script:comExcelWS in $Script:comExcelWB.Worksheets) {
    if ($Script:comExcelWS.Visible) {
        $Script:comExcelWS.Select()
        foreach ($Script:comExcelRNG in $Script:comExcelWS.UsedRange) {
            if ($Script:comExcelRNG.MergeCells) {
                $Script:comExcelMA = $Script:comExcelRNG.MergeArea
                $Script:comExcelRNG.UnMerge()
                                if ($null -ne $Script:comExcelMA.Value2) {
                                    $Script:comExcelMA.Value2 = [String]$Script:comExcelRNG.Value2
                                }
            }
        }
        $Script:comExcelWB.SaveAs("$($WSDestination.FullName)\$($Script:comExcelWS.Name).csv",
            [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV, [Microsoft.Office.Interop.Excel.XlSaveAsAccessMode]::xlNoChange)
    }
}

相关问题