Select 在 Powershell 中使用 ComOject Excel.Application 活动工作表中的所有单元格

Select All Cells in Active Worksheet using ComOject Excel.Application in Powershell

对 Powershell 非常陌生。

情况:

我下面的脚本旨在执行以下操作:

  1. Open New Workbook
  2. Put "This is A1" in the cell 'A1'
  3. Select all cells in the Active Worksheet
  4. Set the selection to TEXT data format

这是我的 Powershell 脚本:

$excel = New-Object -Com Excel.Application
$excel.visible = $true
$book = $excel.Workbooks.Add()
$book.ActiveSheet.Range("A1").Value = "This is A1"
$worksheet = $book.ActiveSheet.UsedRange.Cells
$colcount = $worksheet.columns.count
$copyrange = $worksheet.range("1:$colcount").numberformat = "@"

问题:

我不知道如何在命令中写 Select All 因为当我 运行我的脚本,它只生成 'A1 & B1' TEXT 单元格,其他所有内容都保留为 GENERAL 格式。我想让范围动态化。

这是我在 VBA 中的脚本:

Sub TEXT_FORMAT()

    ActiveCell.FormulaR1C1 = "This is A1"
    Cells.Select
    Selection.NumberFormat = "@"

End Sub

我尝试遵循的脚本:

How to select all in excel using Powershell

任何人都可以帮助我如何使用我的 SELECT ALL 语句使它更加动态?

非常感谢。

试试这个,它对我有用。您可以通过选择 ALL rows(或)ALL columns

来应用数字格式
$excel = New-Object -Com Excel.Application
$excel.visible = $true
$book = $excel.Workbooks.Add()
$worksheet = $book.ActiveSheet
$worksheet.Range("A1").Value2 = "This is A1" # Use the property 'Value2'
$worksheet.Rows.NumberFormat = "@"
# $worksheet.Columns.NumberFormat = "@" # this also sets number format of all cells to 'Text'