我基本上尝试使用PowerShell将Excel中的单元格与另一个工作表中的另一个单元格进行比较。这是我正在使用的代码:
# Define location
$crs = "C:\temp\CRSENGCY_PS.xlsx"
$english = "English"
$welsh = "Welsh"
$SubSection = "SubSection"
# Create instance
$objExcel = New-Object -ComObject Excel.Application
$workBook = $objExcel.Workbooks.Open($crs)
$englishSheet = $workBook.Worksheets.Item($english)
$subSectionSheet = $workBook.Worksheets.Item($SubSection)
$objExcel.Visible = $false
# Num of rows
$engRowMax = 1812
$subRowMax = 677
# Define columns
$rowName, $colName = 1, 1
for ($i=1; $i -le $subRowMax; $i++) {
$SubSectionName = $subSectionSheet.Cells.Item($rowName+$i,2).Text
$3SubSections = $SubSectionName.Substring(0, 3)
for ($i=1; $i -le $engRowMax; $i++) {
$englishName = $englishSheet.Cells.Item($rowName+$i, $colName).Text
$3englishName = $englishName.Substring(0, 3)
if ($3englishName -eq $3SubSections) {
Write-Host("Success")
} else {
Write-Host("Failed" + $3SubSections + " " + $3englishName)
}
}
}
$objExcel.Quit()
我遇到的问题是底部的for
循环只运行一次。内部的for
循环运行正确的次数。如果我删除嵌套的for
循环,它可以正常工作。
答案 0 :(得分:0)
我相信你的问题是嵌套的For循环没有结束。您可能希望在两个For循环中都放置一个 Break 语句,告诉他们您希望它们退出循环的位置。
以下链接可能有助于解释有关 Break 语句的更多信息:
答案 1 :(得分:0)
如果有兴趣的话,这是我的工作脚本 -
# Define location
$crs = "C:\temp\CRSENGCY_PS.xlsx"
$english = "English"
$welsh = "Welsh"
$SubSection = "SubSection"
# Create instance
$objExcel = New-Object -ComObject Excel.Application
$workBook = $objExcel.Workbooks.Open($crs)
$englishSheet = $workBook.Worksheets.Item($english)
$welshSheet = $workBook.Worksheets.Item($welsh)
$subSectionSheet = $workBook.Worksheets.Item($SubSection)
$objExcel.Visible=$false
# Num of rows
$engRowMax = 1812
$subRowMax = 677
# Define columns
$rowName,$colName = 2,1
# Vars
$engSubID = $englishSheet.Cells.Item($rowName+$s,8)
$welSubID = $welshSheet.Cells.Item($rowName+$s,8)
for ($i=0; $i -le 339; $i++)
{
$SubSectionName = $subSectionSheet.Cells.Item($rowName+$i,2).text
$SubSecID = $subSectionSheet.Cells.Item($rowName+$i,1).text
#$3SubSections = $SubSectionName.Substring(0,3)
$SubSecRef = $SubSectionName.Substring(0, $SubSectionName.IndexOf(' '))
#Write-Host($SubSecRef)
for ($s=1; $s -le 1811; $s++)
{
$englishName = $englishSheet.Cells.Item($rowName+$s,$colName).text
#$3englishName = $englishName.Substring(0,$englishName.)
$refno = $englishName.Substring(0, $englishName.IndexOf('.') + 1 + $englishName.Substring($englishName.IndexOf('.') + 1).IndexOf('.'))
if ($SubSecRef -eq $refno)
{
$englishSheet.Cells.Item($rowName+$s,8) = $SubSecID
Write-host("Match!!")
}
else
{
#Write-host("No Match " + $3SubSections + " " + $3englishName)
}
}
Write-Host($i)
}
$workBook.Save()
$workBook.Close()
$objExcel.Quit()