简体   繁体   English

您不能使用 excel 在 powershell 中调用空值表达式的方法

[英]You cannot call a method on a null-valued expression in powershell with excel

I have started learning PowerShell with excel and getting null-valued expression error我已经开始使用 excel 学习 PowerShell 并得到空值表达式错误

#open excel application

$x1 = New-Object -comobject excel.application 

#open excel to show the result in realtime

$x1.Visible = $true

#open the already existing excel to edit

$test = $x1.Workbooks.Open("C:\Users\tushar.v\OneDrive - HCL Technologies Ltd\Documents\test.xlsx")

#to open a specific worksheet

$test2 = $test.worksheets.Item(1).Activate

$test2.Cells.Item(1,1) = "alphatext"

Error:错误:

You cannot call a method on a null-valued expression.
At line:9 char:1
+ $test2.Cells.Item(1,1) = "alphatext"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Also, I am not getting the output in the excel另外,我在 excel 中没有得到 output

First of all, I would advise to use better variable names, so in a larger script it is clear what every variable contains.首先,我建议使用更好的变量名称,因此在较大的脚本中,每个变量都包含什么内容是很清楚的。 $test and $test2 are not really descriptive.. $test$test2不是真正的描述性..

Then for what you have tried:那么对于你所尝试的:

The worksheet's Activate() method does not return an object referencing the activated worksheet as you might think, so you need to first get the worksheet object in a variable and use that to perform the Activate() method.工作表的Activate()方法不会返回引用已激活工作表的 object,因此您需要首先在变量中获取工作表 object 并使用它来执行 Activate() 方法。

Try:尝试:

# create excel application
$excel = New-Object -comobject excel.application 

# open excel to show the result in realtime
$excel.Visible = $true

# open the already existing excel to edit
$workbook  = $excel.Workbooks.Open("D:\Test\blah.xlsx")
# get a reference to the first worksheet in the file
$worksheet = $workbook.WorkSheets.Item(1)
# make this worksheet active
$worksheet.Activate()
# and add content to the cell
$worksheet.Cells.Item(1,1) = "alphatext"

Finally, creating COM objects consumes memory, so after your work is done, you need to tell Windows that it can clean up those objects:最后,创建 COM 对象会消耗 memory,因此在您的工作完成后,您需要告诉 Windows 它可以清理这些对象:

# Don't forget to quit Excel when done (after saving perhaps?) and to remove the created COM objects from memory:

$excel.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($worksheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM