0

I've tried a few ways I've seen on here to get this to work but with no success. Most say use .formula or escape characters. I was able to add normal data to cells but I can't add the formula. I know it works outside of Powershell.

Here's the line:

$WS.Cells.Item(6,4).formula = "='C:\Users\JG\Desktop\Reference\Financial\Test\[$MNE.xlsx]$MNE'!$O$28"

And the error:

Exception from HRESULT: 0x800A03EC At C:\Users\JG\Desktop\Reference\Test\Test2.ps1:47 char:1 + $WS.Cells.Item(6,4).formula = "='C:\Users\JG\Desktop\Reference\ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], COMException + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Any help is appreciated. Thanks.

2
  • 2
    You need to escape the dollar signs in the formula using a backtick - see here Commented Aug 29, 2018 at 1:22
  • That worked. I was sitting here escaping the single quote. Thank you! Commented Aug 29, 2018 at 1:39

2 Answers 2

4

You need to escape the $ in the formula with a backtick `, otherwise $MNE,$O and $28 are interpreted as variables, with no value. The formula then becomes ='C:\Users\JG\Desktop\Reference\Financial\Test\[.xlsx]'!, which is invalid.

Your formula then should be:

"='C:\Users\JG\Desktop\Reference\Financial\Test\[`$MNE.xlsx]`$MNE'!`$O`$28"
Sign up to request clarification or add additional context in comments.

Comments

2

Another solution would be to swap the quotations around. A double quote in PowerShell is a normal string, variables will be expanded when it is eventually interpreted. A single quote in PowerShell is a literal string, no variable expansion can happen inside it.

For example the following $World will be interpreted as a variable and PowerShell will attempt to replace it with the $World variable

 > Write-Output "Hello $World"
Hello

Simply replacing the double quotes with a single quote will stop the variable expansion

> Write-Output 'Hello $World'
Hello $World

To apply it to your problem you would simply flip the quotations

$WS.Cells.Item(6,4).formula = '="C:\Users\JG\Desktop\Reference\Financial\Test\[$MNE.xlsx]$MNE"!$O$28'

Useful to keep in mind :)

2 Comments

Note that Excel still requires the single quotes within the formula, 1 at the beginning of the path and 1 right after the sheet name. I don't think you can just flip the quotations in this particular case.
I was a little unsure about how Excel would deal with the double quote. Not useful for this use case but still useful. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.