Quantcast
Channel: /r/powershell – How to Code .NET
Viewing all articles
Browse latest Browse all 8793

Set Range via Excel COM

$
0
0

We have a current (manual) process for evaluating expiring user accounts. I’d like to automate the generation of the list, and allow supervisors to just update the spreadsheet. The part I’m having trouble with is defining the range for a dropdown menu I’m creating.

Here is the (rough draft) code:

# For testing, file must already exist and be a properly formatted Excel file (.xls/.xlsx) $Excel = "C:ScriptsTest.xlsx" # Create COM object and open $Excel file $ExcelObject = New-Object -ComObject Excel.Application $Workbook = $ExcelObject.Workbooks.Open($Excel) $WorkSheet = $Workbook.Worksheets.Item("Sheet1") $ExcelObject.Visible = $true # Set headers of Excel file Try { $Worksheet.Cells.Item(1, 1) = "FirstName" $Worksheet.Cells.Item(1, 2) = "LastName" $Worksheet.Cells.Item(1, 3) = "Username" $Worksheet.Cells.Item(1, 4) = "Expiration Date" $Worksheet.Cells.Item(1, 5) = "Account Action" $failed = !$? } Catch { # Insert error handling code $failed = $true } # Section commented out for now # Looping Through Items ***Example, validation needed*** # $i = 2 # $Users = Get-ADUser -Filter {<#Filter TBD#>} -Properties AccountExpirationDate # foreach ($User in $Users) { # $objWorksheet.Cells.Item($i, 1) = $User.GivenName # $objWorksheet.Cells.Item($i, 2) = $User.Surname # $objWorksheet.Cells.Item($i, 3) = $User.Samaccountname # $objWorksheet.Cells.Item($i, 4) = $User.AccountExpirationDate # $i++ # } # Set 'Account Action' options for supervisors $Options = "Delete Immediately, Let Account Expire, Extend Access" # Define Range for drop down menu. Apply drop down menu $MenuRange = $WorkSheet.Range("E2:E10") #<--This is where I am not sure how to dynamically set the range. See below for more info. $MenuRange.Validation.add(3,1,1,$Options) # Expand all columns to automatically fit user # **Note, this should occur at the end after all data has been inputted** $Worksheet.Columns.EntireColumn.AutoFit() 

The part above where I’m having trouble is setting the range for the drop down menu in column E. I figured as a starting point I could use the $i variable, since it would only be off by one row. I have tried several ways to have it evaluated within the Range method without success. I have not tried creating a new variable and passing it into the Range method (e.g. $endrange = “e” + “$i”….Range(E2:$endrange).

Any ideas on the best approach is appreciated. Thank you.

submitted by /u/gorlechov
[link] [comments]

The post Set Range via Excel COM appeared first on How to Code .NET.


Viewing all articles
Browse latest Browse all 8793

Trending Articles