Return a reference to an Excel Worksheet from a PowerShell Function

后端 未结 1 1764
[愿得一人]
[愿得一人] 2021-01-27 04:56

For the sake of code readability, I\'d like to move my Excel stuff to a function and leave the worksheet object available to write cell values as my program processes stuff. How

相关标签:
1条回答
  • 2021-01-27 05:18

    If you are looking to get the reference to the worksheet, you can update your code to make sure nothing else is printed / returned besides what you are looking for. As it stands, you are returning two variables..

    $wksht = Create-Excel-Spreadsheet
    
    1. $wksht[0] -> Boolean (True)
    2. $wksht[1] -> Worksheet reference.

    Second index of your return variable will have your spreadsheet reference where first is just a boolean.

    This is a good read from the founder of powershell as to why this happens.

    If you take your code and execute it, you will find that there is a True printed before the object $xl_wksht itself is printed. What you have to do is to make sure nothing else prints on the screen except for the variable/reference you need.

    Change this line in your code and you'll be able to get the reference out.

        $MergeCells.Select() | Out-Null # line 17 of your code. Add | Out-Null. Or, Simply remove this line as it doesnt do anything.
    

    once you have updated your code, you can use a variable to get the value from your method

        $wksht = Create-Excel-Spreadsheet
        $wksht.Cells(5, 1) = "Test"       // Writes Test on Row 5, Col 1.
    
    0 讨论(0)
提交回复
热议问题