Как закрыть приложение Excel, если у меня есть только ссылка на рабочий лист, возвращающаяся из функции PowerShell? - PullRequest
1 голос
/ 17 января 2020

Я задал предыдущий вопрос о Возвращение справочной таблицы Excel из вызова функции . Теперь я хочу использовать PowerShell, чтобы закрыть приложение Excel после его сохранения.

Функция под названием

Function Create-Excel-Spreadsheet() {
    [CmdletBinding()]
    Param (
        [Parameter(Position=0)]
        [string]$title_row='1',
        [Parameter(Position=1)]
        [string]$header_row='2',
        [Parameter(Position=2)]
        [string]$data_row_start='3',
        [Parameter(Position=3)]
        [string]$data_row_end='10'
    )

    # open excel
    $excel = New-Object -ComObject excel.application
    $excel.visible = $True
    $workbook = $excel.Workbooks.Add()
    $xl_wksht= $workbook.Worksheets.Item(1)
    $xl_wksht.Name = 'Cut-off'   #give the worksheet a name
    $xl_wksht.Cells.Item($title_row, 1)= 'Cut-off Processing Ran ' + $startday + ' at ' + $starttime_str
    $MergeCells = $xl_wksht.Range("A1:Q1")
    $MergeCells.MergeCells = $true

    #formatting the title and giving it a font & color
    $xl_wksht.cells($title_row, 1).HorizontalAlignment = -4108   # center the title
    $xl_wksht.cells.Item($title_row,1).Font.Size = 18
    $xl_wksht.cells.Item($title_row,1).Font.Bold = $True
    $xl_wksht.cells.Item($title_row,1).Font.Name = "Cambria"
    $xl_wksht.cells.Item($title_row,1).Font.ThemeFont = 1
    $xl_wksht.cells.Item($title_row,1).Font.ThemeColor = 4
    $xl_wksht.cells.Item($title_row,1).Font.ColorIndex = 55
    $xl_wksht.cells.Item($title_row,1).Font.Color = 8210719
    $xl_wksht.cells.Item($title_row,1).Font.Color = 8210719
    $xl_wksht.Rows[$title_row].RowHeight = 39
    $xl_wksht.Rows[$title_row].VerticalAlignment = 2

    $xl_wksht.Rows[$header_row].WrapText = $True
    $xl_wksht.Rows[$header_row].Font.Bold = $True
    $xl_wksht.Rows[$header_row].columnWidth = 12.57
    $xl_wksht.Rows[$header_row].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 1).value2 = 'Current Load Date'
    $xl_wksht.Columns[1].HorizontalAlignment = -4108
    $xl_wksht.Columns[1].NumberFormat = "@"

    $xl_wksht.cells.Item($header_row, 2).value2 = 'Export File Type'
    $xl_wksht.Columns[2].columnWidth = 26

    $xl_wksht.cells.Item($header_row,3).value2 = 'File Name to Downloaded'
    $xl_wksht.Columns[3].columnWidth = 37

    $xl_wksht.cells.Item($header_row,4).value2 = 'Source Path'
    $xl_wksht.Columns[4].columnWidth = 23

    $xl_wksht.cells.Item($header_row,5).value2 = 'File Available?'
    $xl_wksht.Columns[5].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row,6).value2 = 'Already Loaded in DB?'
    $xl_wksht.Columns[6].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row,7).value2 = 'Checking Database.Owner.Table'
    $xl_wksht.Columns[7].columnWidth = 50

    $xl_wksht.cells.Item($header_row,8).value2 = 'Query Count for Current Date'
    $xl_wksht.Columns[8].Style.NumberFormat = '#,##0'

    $xl_wksht.cells.Item($header_row,9).value2 = 'Previous Load Date'
    $xl_wksht.Columns[9].HorizontalAlignment = -4108
    $xl_wksht.Columns[9].NumberFormat = "@"

    $xl_wksht.cells.Item($header_row,10).value2 = 'Query Count for Previous Load'
    $xl_wksht.cells.Item($header_row,11).value2 = 'Diff between Current and Previous Load Count'

    $xl_wksht.cells.Item($header_row,12).value2 = 'Pct Diff between Current and Previous Load Count'
    # Add formatting for the percentage column
    $fmt_range_start=('L' + $data_row_start)
    $fmt_range_end=('L' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0.000000%"

    $xl_wksht.cells.Item($header_row, 13).value2 = 'Compressed File Size'
    $xl_wksht.Columns[13].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 14).value2 = 'Successfully Downloaded and Unzipped File'
    $xl_wksht.Columns[14].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 15).value2 = 'Un-Zip Time (Mins:Secs,Fract Secs)'
    #$xl_wksht.columns.item('n').NumberFormat = "@"  #alternative notation using letter of column
    $xl_wksht.Columns[15].columnWidth = 24
    $xl_wksht.columns[15].NumberFormat = "@"
    $xl_wksht.Columns[15].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 16).value2 = 'Un-Zipped File Size'    
    $xl_wksht.Columns[16].columnWidth = 14
    $xl_wksht.Columns[16].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 17).value2 = 'Un-Zipped File Line Count'

    $xl_wksht.cells.Item($header_row, 18).value2 = 'Time to Count Lines (mins:secs,fract secs)'
    $xl_wksht.Columns[18].columnWidth = 24
    $xl_wksht.columns[18].NumberFormat = "@"
    $xl_wksht.Columns[18].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 19).value2 = 'Parse File Directory'
    $xl_wksht.Columns[19].columnWidth = 36

    $xl_wksht.cells.Item($header_row, 20).value2 = 'Parse File Name'
    $xl_wksht.Columns[20].columnWidth = 44

    $xl_wksht.cells.Item($header_row, 21).value2 = 'Fields Per Line'

    $xl_wksht.cells.Item($header_row, 22).value2 = 'Time to Parse File (hrs:mins:secs,fract secs)'
    $xl_wksht.Columns[22].columnWidth = 24
    $xl_wksht.columns[22].NumberFormat = "@"
    $xl_wksht.Columns[22].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 23).value2 = 'Total Line Count During Parsing'
    $fmt_range_start=('W' + $data_row_start)
    $fmt_range_end=('W' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0"

    $xl_wksht.cells.Item($header_row, 24).value2 = 'Count of Lines Parsed for Loading'
    $fmt_range_start=('X' + $data_row_start)
    $fmt_range_end=('X' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0"

    $xl_wksht.cells.Item($header_row, 25).value2 = 'Count of Unloadable Lines'
    $fmt_range_start=('Y' + $data_row_start)
    $fmt_range_end=('Y' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0"

    $xl_wksht.cells.Item($header_row, 26).value2 = 'Pct of Unloadable Lines'
    # Add formatting for the percentage column
    $fmt_range_start=('Z' + $data_row_start)
    $fmt_range_end=('Z' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0.000000%"

    $xl_wksht.cells.Item($header_row, 27).value2 = 'Error File Directory'
    $xl_wksht.Columns[27].columnWidth = 36

    $xl_wksht.cells.Item($header_row, 28).value2 = 'Error File Name'
    $xl_wksht.Columns[28].columnWidth = 44

    $xl_wksht.cells.Item($header_row, 29).value2 = 'Staging Directory'
    $xl_wksht.Columns[29].columnWidth = 45

    $xl_wksht.cells.Item($header_row, 30).value2 = 'Successfully Copied to Staging Directory'
    $xl_wksht.cells.Item($header_row, 31).value2 = 'Local Processing Files Removed'

    $xl_wksht.cells.Item($header_row, 32).value2 = 'Start Time for DB Load'
    $xl_wksht.columns[32].NumberFormat = "@"
    $xl_wksht.Columns[32].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 33).value2 = 'End Time for DB Load'
    $xl_wksht.columns[33].NumberFormat = "@"
    $xl_wksht.Columns[33].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 34).value2 = 'Total Time to Load File (hrs:mins:secs)'
    $xl_wksht.Columns[34].columnWidth = 20
    $xl_wksht.columns[34].NumberFormat = "@"
    $xl_wksht.Columns[34].HorizontalAlignment = -4108

    $xl_wksht.cells.Item($header_row, 35).value2 = 'Count of Rows Uploaded'
    $fmt_range_start=('AI' + $data_row_start)
    $fmt_range_end=('AI' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0"

    $xl_wksht.cells.Item($header_row, 36).value2 = 'Count of Rows Not Loaded'
    $fmt_range_start=('AJ' + $data_row_start)
    $fmt_range_end=('AJ' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0"

    $xl_wksht.cells.Item($header_row, 37).value2 = 'Pct of Rows Not Loaded'
    # Add formatting for the percentage column
    $fmt_range_start=('AK' + $data_row_start)
    $fmt_range_end=('AK' + $data_row_end)
    $fmt_range="$fmt_range_start" + ":" + "$fmt_range_end"
    $FormatRange = $xl_wksht.Range($($fmt_range))
    $FormatRange.NumberFormat = "#,##0.000000%"

    return $xl_wksht
}

Я делаю кучу вещей, и тогда я готов очистить в конце основной программы.

Из основной программы

    $xl_wksht.Application.DisplayAlerts = $False  # don't show overwrite warning if it displays
    $xl_wksht.Application.ActiveWorkbook.SaveAs("$savePath")
    $xl_wksht.Application.ActiveWorkbook.Close($false) 
    $xl_wksht.Application.Quit()

Кажется, все работает, пока я не доберусь до Quit (). Затем я получаю сообщение об ошибке «Вы не можете вызвать метод с нулевым выражением».

1 Ответ

1 голос
/ 17 января 2020

Не проверено, но, возможно, попробуйте сначала получить ссылку на приложение Excel перед закрытием книги:

$xl = $xl_wksht.Application
... hide alerts, saveas and close
$xl.Quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...