I have been working with Excel for the past month or so, mainly doing reports for a research project, and recently I realized that I could write a powershell script that can speed up my work.
Example Table:
+-------+-----------+--------+-------------+------+------+------+------+------+------+------+------+
| text1 | Direction | Origin | Destination | num1 | num2 | num3 | num4 | num5 | num6 | num7 | num8 |
+-------+-----------+--------+-------------+------+------+------+------+------+------+------+------+
| Test1 | Import | Place3 | Place1 | x1 | x4 | x7 | x10 | x13 | x16 | x19 | x22 |
+-------+-----------+--------+-------------+------+------+------+------+------+------+------+------+
| Test2 | Export | Place4 | Place2 | x2 | x5 | x8 | x11 | x14 | x17 | x20 | x23 |
+-------+-----------+--------+-------------+------+------+------+------+------+------+------+------+
| Test3 | Import | Place5 | Place1 | x3 | x6 | x9 | x12 | x15 | x18 | x21 | x24 |
+-------+-----------+--------+-------------+------+------+------+------+------+------+------+------+
So, what I do is that I open a xlsx file, that contains rows filled with package delivery details, seperate imports from exports and then compare Imports with exports and if there are missing desinations (more on that later) I will add the destinations as values and then assign "0" to their individual columns.
Right now I've written the following lines and I don't know where to go from there:
# Create Excel Object
$Excel = New-Object -ComObject Excel.Application
# Prompt for file path
$Filepath = Read-Host -Prompt 'Where can I find your file? (Path\to\File.xlsx)'
# Open File from inside PowerShell
$Workbook = $Excel.Workbooks.Open($Filepath)
# Use two variables to assign two sheets
$ws1 = $wb.worksheets | where {$_.name -eq "sheet1"}
$ws2 = $wb.worksheets | where {$_.name -eq "sheet2"}
# Assign used range to a variable
$mainRng = $ws1.usedRange
# Select Range
$mainRng.Select()
#Find a test value
$ValueSearch = $mainRng.Find("Import")
The reason I'm now stuck is because I get Null values when I'm selecting a range.
Error Message:
- $mainRng.Select()
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
How can I fix that so I can proceed with my development? Because after that I will loop through every row and, using a conditional, I will seperate Import from Export.
Place1is not present both as a Destination and Origin, which in lamest terms means that the count of rows/records for Destination and Origin must be equal) After that I'll try to connect with a Microsoft Access to automatically upload my results.