How to select Excel range in powershell - excel

I have the following code in a function:
function Excel2PPT{
param ($xslx, $targetsheet, $targetrange, $pptx, $targetslide, $npath)
$Excel = New-Object -ComObject Excel.Application
$workbook = $Excel.workbooks.open($xslx)
$Excel.Visible= $true
$worksheet = $workbook.worksheets.Item($targetsheet)
$range = $worksheet.Range($targetrange)
$range.select()
$range.copy()
I am using it in another function which passes to it "A1:O12" as $targetrange
This worked in previous testing but now yields an error and unexpected behavior.
I reference it as:
Excel2PPT $IncomingABCExcel 1 'A1-O12' $testPPT2 $Targetslide $testPPT3
The error is:
Exception from HRESULT: 0x800A03EC
At C:\...\Excel2PPT.ps1:16 char:1
+ $range = $worksheet.Range($targetrange)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
You cannot call a method on a null-valued expression.
At C:\...\Excel2PPT.ps1:17 char:1
+ $range.select()
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\...\Excel2PPT.ps1:18 char:1
+ $range.copy()
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
What can I do to fix it? It should be copying and pasting $targetrange to the intended PPT slide but it appears to be copying and pasting "$IncomingABCExcel" (not the variable, the variable name) onto the slide.

The issue you are having is that you are using 'A1-012' As the range. This should be 'A1:012':
function Excel2PPT {
param ($xslx, $targetsheet, $targetrange, $pptx, $targetslide, $npath)
$Excel = New-Object -ComObject Excel.Application
$workbook = $Excel.workbooks.open($xslx)
$Excel.Visible= $true
$worksheet = $workbook.worksheets.Item($targetsheet)
$range = $worksheet.Range($targetrange)
$range.select()
$range.copy()
}
Excel2PPT $IncomingABCExcel 1 'A1:O12' $testPPT2 $Targetslide $testPPT3

Related

Powershell generic error: Exception from HRESULT: 0x800A03EC

I know this is a very generic error message and I have spent many hours looking through similar questions without any luck.
Here is my PowerShell script producing this error:
$ExcelObject = New-Object -ComObject excel.application
$excelProcessId = ((get-process excel | select MainWindowTitle, ID, StartTime | Sort StartTime)[-1]).Id
$ExcelObject.visible = $true
$ExcelObject.DisplayAlerts = $true
$folderpath = "C:\myfiles\TESTER.xlsx"
$Workbook = $ExcelObject.Workbooks.Open($folderpath)
$WorkSheet = $Workbook.Worksheets.Item("TAB1")
$sourceList = "value1,value2,value3"
$missing = [system.type]::missing
$sourceRange = $WorkSheet.Range("A3:A22")
$sourceRange.Validation.add(3,1,$missing,$sourceList,$missing)
$Workbook.save()
$Workbook.close()
$ExcelObject.Quit()
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook)
[void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelObject)
[GC]::Collect()
Remove-Variable ExcelObject
Stop-Process -Id $excelProcessId -Force
resulting error:
Exception from HRESULT: 0x800A03EC
At line:11 char:1
+ $sourceRange.Validation.add(3,1,$missing,$sourceList,$missing)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
I have tried to use the value list directly but same error:
$sourceRange.Validation.add(3,1,$missing,"value1,value2,value3",$missing)
I replaced the $missing but same error:
$sourceRange.Validation.add(3,1,1,$sourceList)
I have no more ideas on how to resolve this issue and would appreciate any suggestions.
Thanks a lot for your time.
I have found the problem: the specified range had to be cleared of any existing validation:
$sourceRange = $WorkSheet.Range("A3:A22")
$sourceRange.Validation.Delete()
$sourceRange.Validation.add(3,1,$missing,$sourceList,$missing)
I feel a little embarrassed, but maybe it is of use to someone down the line.

Powershell How transfer cell value from column C to Column B , one by one

I have below powershell script:
$NewExcelFile = "F:\test\test-data123.xlsx"
$newExcel = New-Object -ComObject Excel.Application
$newwb = $newExcel.Workbooks.Open($NewExcelFile)
$sheet=$newwb.Worksheets.Item(1)
$sheet.Name = 'sheet1'
$importedExcelRows = Import-Excel $NewExcelFile
$q=$($importedExcelRows.Count)
$q1="B"+$q
$r1 = $sheet.Range("R2:$q1")
$r1.cut()
$i1="C"+$q
$r2 = $sheet.Range("I2:$i1")
$sheet.Paste($r2)
$newwb.Close($true)
$newExcel.Quit()
I have below Excel:
I want to change cell on by one like I wanna cell value like cell C2 to cell B2
**Please find below error message Error: **
Cannot convert the "OfficeOpenXml.ExcelPackage" value of type "OfficeOpenXml.ExcelPackage" to type "OfficeOpenXml.ExcelPackage".
At C:\Program Files\WindowsPowerShell\Modules\ImportExcel\7.4.0\Public\Import-Excel.ps1:122 char:17
+ ... $ExcelPackage = New-Object -TypeName OfficeOpenXml.ExcelP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\ImportExcel\7.4.0\Public\Import-Excel.ps1:124 char:24
+ else { $ExcelPackage.Load($stream) }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\ImportExcel\7.4.0\Public\Import-Excel.ps1:229 char:47
+ ... if ($Path) { $stream.close(); $ExcelPackage.Dispose() }
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Failed importing the Excel workbook 'F:\test\test-data1.xlsx' with worksheet '': Cannot index into a null array.
At C:\Program Files\WindowsPowerShell\Modules\ImportExcel\7.4.0\Public\Import-Excel.ps1:227 char:21
+ ... catch { throw "Failed importing the Excel workbook '$Path' with w ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Failed importin...o a null array.:String) [], RuntimeException
+ FullyQualifiedErrorId : Failed importing the Excel workbook 'F:\test\test-data1.xlsx' with worksheet '': Cannot index into a null arr
ay.
I'm not sure why are you using ComObject having access to Import-Excel. If your intent is to replace the values of the current value column with the values of change value column, using Import-Excel you can treat it as if it were a Csv:
# Export a Test Xlsx
#'
no,currentVal,changeVal
1,a1,b1
2,a2,b2
3,a3,b3
4,a4,b4
5,a5,b5
6,a6,b6
'# |
ConvertFrom-Csv |
Export-Excel ./test.xlsx -WorksheetName example
# Import it
$xlsx = Import-Excel ./test.xlsx -WorksheetName example
# Replace the Values
$xlsx | ForEach-Object {
$_.currentVal = $_.changeVal
}
# Save the new Xlsx
$xlsx | Export-Excel ./test2.xlsx -WorksheetName example2
This would be the result of the above operation, still, it's unclear to me what should happen with the "replaced values" of current value column and what should happen with the change value column after performing the operation.
no currentVal changeVal
-- ---------- ---------
1 b1 b1
2 b2 b2
3 b3 b3
4 b4 b4
5 b5 b5
6 b6 b6

Get data from Microsoft Access table and put into Microsoft Excel workbook as QueryTable - powershell script failed

Here is my piece of code:
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $true
$objExcel.SheetsInNewWorkbook = 1
$objWorkBook = $objExcel.Workbooks.Add()
$objWorkSheet = $objWorkBook.Sheets.Item(1)
$objWorkSheet.Activate()
$strHome = "C:\share"
$strAccessFile = $strHome + "\db1.accdb"
$strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=$strAccessFile;Persist Security Info=True;"
$adOpenStatic = 3
$adLockOptimistic = 3
$objConnection = New-Object -ComObject ADODB.Connection
$objConnection.Open($strConnectionString)
$objRecordSet = New-Object -ComObject ADODB.RecordSet
$strAccessString = "SELECT * FROM Table"
$objRecordSet.Open($strAccessString,$objConnection,$adOpenStatic,$adLockOptimistic)
$objRecordSet.Fields.Item("Text").Value
$oRange = $objWorkSheet.Range("B4")
$oRez = $objWorkSheet.QueryTables.Add($objRecordSet,$oRange)
Excel was opened, the same with Access recordset. Field "Text" value was shown.
Last line of code produce error:
Exception calling "Add" with "2" argument(s): "Parameter is not correct. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))"
At C:\share\dataconn_test.ps1:26 char:1
+ $oRez = $objWorkSheet.QueryTables.Add($objRecordSet,$oRange)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
WHY? What I'm doing wrong?

why do I get a null valued expression error when converting a csv file to excel using powershell?

I have a powershell script that downloads a CSV file from yahoo finance, and my goal is to convert it to an excel file (.xlsx). The script is:
$path = "D:"
$client = New-Object System.Net.WebClient
$url = "http://download.finance.yahoo.com/d/quotes.csv?s=EDV,VEA,VWO,VHT,BND,VTI&f=sl1d1t1c1ohgv&e=.csv"
$csv_filename = Join-Path $path "prices.csv"
$client.DownloadFile($url, $csv_filename)
$xl_filename = Join-Path $path "prices.xlsx"
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true
$wb = $xl.Workbooks.OpenText($csv_filename)
$wb.SaveAs($xl_filename, 51)
$wb.Close()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
The script is located in `D:\get_prices.ps1' and I execute it with
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File D:\get_prices.ps1
When I run it I get two errors:
You cannot call a method on a null-valued expression.
At D:\get_prices.ps1:14 char:11
+ $wb.SaveAs <<<< ($xl_filename, 51)
+ CategoryInfo : InvalidOperation: (SaveAs:String) [], RuntimeExc
eption
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At D:\get_prices.ps1:15 char:10
+ $wb.Close <<<< ()
+ CategoryInfo : InvalidOperation: (Close:String) [], RuntimeExce
ption
+ FullyQualifiedErrorId : InvokeMethodOnNull
The conversion code is adapted from this question-answer (How to export a CSV to Excel using Powershell).
I looked at the documentation for Workbook.SaveAs and as far as I nkow Im using it correctly, and the file format (the 51 argument) is correct too based on this. I also looked at the docs for Workbook.Close and that all looks correct too.
I'm using powershell v2.0 (according to get-host) and Excel 2013 on Windows 7 x64.
What am I doing wrong?
$xl.Workbooks.OpenText returns void not a workbook.
Make this change:
$xl.Workbooks.OpenText($csv_filename)
$wb=$xl.ActiveWorkbook

How to read cell data in excel and output to command prompt

I'm a sys admin and I am trying to learn how to use powershell... I have never done any type of scripting or coding before and I have been teaching myself online by learning from the technet script centre and online forums.
What I am trying to accomplish is to open an excel spreadsheet get information from it (usernames and password) and then output it into the command prompt in powershell. When ever I try to do this I get an Exception calling "InvokeMember" anyway, here is the code I have so far:
function Invoke([object]$m, [string]$method, $parameters)
{
$m.PSBase.GetType().InvokeMember(
$method, [Reflection.BindingFlags]::InvokeMethod, $null, $m, $parameters,$ciUS )
}
$ciUS = [System.Globalization.CultureInfo]'en-US'
$objExcel = New-Object -comobject Excel.Application $objExcel.Visible = $False $objExcel.DisplayAlerts = $False
$objWorkbook = Invoke $objExcel.Workbooks.Open "C:\PS\User Data.xls" Write-Host "Numer of worksheets: " $objWorkbook.Sheets.Count
$objWorksheet = $objWorkbook.Worksheets.Item(1) Write-Host "Worksheet: " $objWorksheet.Name
$Forename = $objWorksheet.Cells.Item(2,1).Text $Surname = $objWorksheet.Cells.Item(2,2).Text
Write-Host "Forename: " $Forename Write-Host "Surname: " $Surname
$objExcel.Quit() If (ps excel) { kill -name excel}
I have read many different posts on forums and articles on how to try and get around the en-US problem but I cannot seem to get around it and hope that someone here can help!
Here is the Exeption problem I mentioned:
Exception calling "InvokeMember" with "6" argument(s): "Method 'System.Management.Automation.PSMethod.C:\PS\User Data.x
ls' not found."
At C:\PS\excel.ps1:3 char:33
+ $m.PSBase.GetType().InvokeMember <<<< (
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Numer of worksheets: You cannot call a method on a null-valued expression. At C:\PS\excel.ps1:18 char:45 + $objWorksheet = $objWorkbook.Worksheets.Item <<<< (1) + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
Worksheet: You cannot call a method on a null-valued expression. At C:\PS\excel.ps1:21 char:37 + $Forename = $objWorksheet.Cells.Item <<<< (2,1).Text + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression. At C:\PS\excel.ps1:22 char:36 + $Surname = $objWorksheet.Cells.Item <<<< (2,2).Text + CategoryInfo : InvalidOperation: (Item:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
Forename:
Surname:
This is the first question I have ever asked, try to be nice! :))
Many Thanks
Max
I find OLE DB and the Office 2007 drivers a little easier to use. If you don't have Office 2007, you can download the drivers from MS.
$filepath = 'C:\Users\u00\documents\backupset.xlsx'
$connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"
#Connection String for Excel 2003:
#$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";"
$qry = 'select * from [sheet1$]'
$conn = New-Object System.Data.OleDb.OleDbConnection
$conn.ConnectionString = $connString
$conn.open()
$cmd = new-object System.Data.OleDb.OleDbCommand($qry,$conn)
$da = new-object System.Data.OleDb.OleDbDataAdapter($cmd)
$dt = new-object System.Data.dataTable
[void]$da.fill($dt)
$conn.close()
$dt
thanks for your help...I have fixed the problem! I was using PowerShell V2 CTP2, now I have upgraded to CTP3 this has fixed the language barrier problem and I can now run scripts without worrying about the invoke function and all is fine!
Many Thanks
Max

Resources