I cannot retrieve VBA function result from an Excel document into Powershell script.
Powershell file
$suite = "<some_path>"
$excel = new-object -comobject excel.application
$workbook = $excel.workbooks.open($suite)
$specs = $excel.Run("ThisWorkbook.ftp_specs")
IF([string]::IsNullOrEmpty($specs)) {
Write-Host "Your string is EMPTY or NULL"
} else {
Write-Host "Your string is not EMPTY"
}
Excel file (in ThisWorkbook)
Function ftp_specs()
ftp_specs = "hello"
End Function
Powershell run result
Your string is EMPTY or NULL
MS Office VBA Reference states Application.Run returns a Variant.
Nothing i've seen on the web in the past few hours hints at anything relevant.
You don't need ThisWorkbook (?) namespace. Just use Run method with the function name. Like so:
$specs = $excel.Run("ftp_specs")
Related
Edit: Ended up finding out what was causing it, but unsure why this works. The fix was to add this line after the excel object was created:
$excel.DisplayAlerts = $False
I'm using PowerShell and trying to delete an existing excel worksheet and then recreate it. My environment is locked down for modules, so unfortunately I can't use ImportExcel or other similar modules. I'm a bit new to PowerShell so apologies if the code is messy, but here's what I currently have:
$TodaysDate = Get-Date -Format "yyyy-MM-dd"
# Open a new excel object
$excel = New-Object -ComObject excel.application
$excel.visible = $False
# If a workbook does not already exist, create one
# If a workbook does exist, open it.
if (-not(Test-Path -Path $ExistingExcelFile -PathType Leaf)) {
$workbook = $excel.Workbooks.Add()
# Delete the automatically generated sheet
$workbook.WorkSheets.Item("Sheet1").Delete()
} else {
$workbook = $excel.Workbooks.Open($ExistingExcelFile)
}
# If a worksheet with todays date already exists, delete it so we can start fresh
if (($TodaysDate -in $($workbook.Worksheets).Name)) {
$TodaysWrkSheet = $workbook.WorkSheets.Item($TodaysDate)
$TodaysWrkSheet.Activate()
$TodaysWrkSheet.Delete()
}
#Add the worksheet and set the name
$WrkSheet = $workbook.Worksheets.Add()
$WrkSheet.Name = $TodaysDate
# If the summary page exists, delete it so we can start fresh
if (("Summary" -in $($workbook.Worksheets).Name)) {
$SummaryWrkSheet = $workbook.WorkSheets.Item("Summary")
$SummaryWrkSheet.Activate()
$SummaryWrkSheet.Delete()
}
$SummaryPage = $workbook.Worksheets.Add()
$SummaryPage.Name = "Summary"
This is the error I get when it tries to create the new sheet with todays date:
That name is already taken. Try a different one.
The second part with the summary page works fine and it finds/deletes/recreates it, so I'm assuming it's a problem with $TodaysDate, but why? The if statement block of code for ($TodaysDate -in $($workbook.Worksheets).Name) gets hit, would there be a problem with $TodaysWrkSheet = $workbook.WorkSheets.Item($TodaysDate)? It creates the sheet just fine as long as it doesn't exist already, so it at least doesn't complain creating a sheet name with $TodaysDate. I've been trying for a while to figure out why but haven't been having any luck.
Any help is appreciated.
How do I create a function in powershell that runs a macro in an Excel workbook?
I've tried the following:
Function xlRunMacro($excel, $macroname){
try{
$excel.Run($macroname)
}catch{
echo $error
$key = 'Open-Excel';
$date = Get-Date -Format 'yyyy-MM-dd';
Log-Error $key $date;
$error.Clear()
}
}
$macroname = "'delete_old'"
$setexcel = New-Object -ComObject Excel.Application
$currentworkbook = $setexcel.Workbooks.Open("${paths}${files}")
xlRunMacro($setexcel, $macroname)
However, I get this error:
Method invocation failed because [System.String] does not contain a method named 'Run'.
Any ideas please?
As #Lee_Dailey mentioned, params need to be separated.
To be on the safe side generally, it's a good idea for functions to accept params by name rather than position.
e.g.
Function xlRunMacro{
param(
$excel,
[string]$macroname
)
$excel.Run($macroname)
}
xlRunMacro -excel $setexcel -macroname $macroname
I have this problem where i have 2 files and the output are:
value from file A is "No data"
value from file B is "prior to versions 0.9.8zd"
when I tried to write it on excel cell using powershell, value B always override value A. How to prevent this?
$outlook = new-object -comobject outlook.application
$dir="c:\users\john\desktop\"
$msgs=get-childitem $dir -filter "*.msg"
$rgx="blabla"
$regex="blablabla"
$xl=New-Object -ComObject Excel.Application
$xl.visible=$true
$wkbk=$xl.workbooks.add()
$wkbk.worksheets.add()
$wksht=$workbook.worksheets.item(1)
$wksht.name="TEST"
$wksht.cells.item(1,11)="Version(s)"
foreach($msg in $msgs)
{
$msg=$outlook.CreateitemFromTemplate($dir+$msg)
$body=$msg.body
if($body -match $rgx)
{
#echo "true"
$version=$body|select-string -pattern $regex -allmatches |%{$_.matches}|%{$_.value}
}
$row=$wksht.usedrange.rows.count+1
$usedrange=$wksht.usedrange
$usedrange.entirecolumn.autofit()|out-null
if([string]::IsNullOrEmpty($version))
{
$wksht.cells.item($row,11)="No data"
}
else
{
$wksht.cells.item($row,11)=$version
}
Expected result :
No Data <----first row,
prior to versions 0.9.8zd <-------2nd row
But what I got :
prior to versions 0.9.8zd <----first row,
prior to versions 0.9.8zd <-------2nd row
Your help highly appreciated. That's basically the whole code. do I missing something
I'm currently trying to grab a specific worksheet from an Excel file in PowerShell and I'm receiving the error "You cannot call a method on a null-valued expression". PowerShell picks up the workbook and even that the property Worksheet exists, yet it does not recognize item(1).
$excel = "C:\budget.xlsx"
$ex = New-Object -ComObject Excel.Application
$ex.Visible = $true
$wb = $ex.Workbooks.Open($excel)
$ws = $wb.Worksheets.item(1) # This line errors
When accessing Excel worksheets, this is the syntax (for instance, see this code, and this is just one of many examples). Is there something else that needs to be loaded in order to do this? After searching the 'net, I can't find anyone else loading or using another syntax.
Hi I'm using a simple Powershell script to convert CSV files to XLSX files. However Excel ignores the list seperator and puts all data in the first column.
The list seperator is configured correctly (Start > Control Panel > Regional and Language Options -> Additional Settings)
Manually opening the files from Windows Explorer works fine.
However, when opening the CSV in Excel using:
Function Convert-toExcel {
$xl = new-object -comobject excel.application
$xl.visible = $true
$Workbook = $xl.workbooks.OpenText("$csvfile")
$Worksheets = $Workbooks.worksheets
}
Everything is put into the first column...
Accoriding to Powershell the list seperator is configured correctly:
(Get-Culture).textinfo
ListSeparator : ,
Try adding the DataType argument to the OpenText method. It appears to take magic arguments.
VBA:
Workbooks.OpenText filename:="DATA.TXT", dataType:=xlDelimited, tab:=True
I would guess in powershell it accepts a hash, so:
$xl.Workbooks.OpenText(#{Filename = $CSVFile; dataTyype = "xlDelimited", other = $true; otherchar=':' })
However, I've no way to test this currently.
The following script works for me. The one change in functionality I made was that I set Excel.visible to false.
Function Export-CSVToXLS {
Param(
[String]$CsvFileLocation
,[String]$ExcelFilePath
)
If (Test-Path $ExcelFilePath )
{
Remove-Item -Path $ExcelFilePath
}
$FixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$Excel.Workbooks.OpenText($CsvFileLocation)
$Excel.ActiveWorkbook.SaveAs($ExcelFilePath,$FixedFormat)
$Excel.Quit()
Remove-Variable -Name Excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
}
Export-CSVToXLS -CsvFileLocation "C:\Temp\CSV.csv" -ExcelFilePath "C:\Temp\XLS.xlsx"
I compiled this based off of information on the following webpages:
http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/09/copy-csv-columns-to-an-excel-spreadsheet-by-using-powershell.aspx
https://social.technet.microsoft.com/Forums/en-US/919459dc-3bce-4242-bf6b-fdf37de9ae18/powershell-will-not-save-excel-file?forum=winserverpowershell
Your original code works fine. My guess is your delimiter in excel just isn't a ",". I've seen this go wrong loads of time. The ps culture has nothing to do with it
Use `t (Powershell code for the tab character) instead of , (a comma).
Excel defaults at opening to using text to columns import with tab as the separator.