【问题标题】:Powershell 1.0 Excel Automation - Problem with "Font.ColorIndex"Powershell 1.0 Excel 自动化 - “Font.ColorIndex”问题
【发布时间】:2010-12-06 17:39:44
【问题描述】:

我正在尝试在 Powershell 1.0 中自动化 Excel,但在尝试应用单元格“Font.ColorIndex”属性时遇到问题。

以下Microsoft KB 文章详细介绍了当运行脚本的计算机具有“en-us”以外的区域设置时 Excel 自动化的 BUG

当我手动将语言环境和区域设置更改为“en-us”并且仅在设置为“en-gb”时在最后一行失败

$Excel = New-object -com Excel.Application 
$culture = [System.Globalization.CultureInfo]'en-us'
$Book = $Excel.Workbooks.psbase.gettype().InvokeMember("Add", 
       [Reflection.BindingFlags]::InvokeMethod, 
       $null, $Excel.Workbooks, $null, $culture)
$Sheet = $Book.Worksheets.Item(1)
$Excel.Visible = $True
$Sheet.Cells.Item(1,1).FormulaLocal = "test"
$Sheet.Cells.Item(1,1).Font.ColorIndex = 3

如前所述,如果我的语言环境设置为“en-gb”,则脚本可以正常工作,直到它失败的最后一行:

在此对象上找不到属性“ColorIndex”;确保它存在并且是可设置的。 在 :line:10 字符:29 + $Sheet.Cells.Item(1,1).Font。

有没有人知道如何解决这个问题(当然,除了将我的语言环境设置为“en-us”!!)

谢谢 -马克

【问题讨论】:

    标签: excel powershell


    【解决方案1】:

    从知识库文章中可以看出,解决方法都涉及将区域性设置为 en-US,除非您想在 PC 上安装 MUI for Office。好消息是,您可以在脚本中为有问题的代码临时设置文化为 en-US。以下脚本是很久以前的PowerShell team posted,但仍然很方便:

    Function Using-Culture (
    [System.Globalization.CultureInfo]$culture = `
        (throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"),
    [ScriptBlock]$script= `
        (throw "USAGE: Using-Culture -Culture culture -Script {scriptblock}"))
    {
        $OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
        trap 
        {
            [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
        }
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
        Invoke-Command $script
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
    }
    

    像这样执行最后一行,看看是否有效:

    Using-Culture en-US { $Sheet.Cells.Item(1,1).Font.ColorIndex = 3 }
    

    【讨论】:

    • 感谢 Keith,但我一直无法让这个工作,并且看到其他人说这对他们也不起作用的 cmets。
    • 您是否尝试在 Using-Culture 函数中运行所有 Excel 脚本?我已经使用这个函数来测试 PowerShell 2.0 中的本地化数据部分,所以我知道“一般”它可以工作。不过也许不适用于 Excel。
    • 是的,在函数中尝试过。我同意“一般”它确实有效并且是正确的解决方案,但是不适用于excel。我认为最好的解决方案是编写 HTML 输出并保存为 .xls 格式?还不确定,但会玩弄它。感谢您的努力
    猜你喜欢
    • 2010-10-02
    • 2012-06-15
    • 2018-08-31
    • 1970-01-01
    • 2017-10-02
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    相关资源
    最近更新 更多