确定单元是否存在于Powershell Excel COM的指定范围内

例如,我期待确定以下逻辑:

if (B2 in A1:B20) # if cell B2 is within the range A1:B20 { return $true } 

有没有在Excel中的function,可以用于这样的事情? 我读了= COUNTIF()函数,但无法得到它的工作。 再次,这是使用PowerShell中的Excel COM对象。

谢谢

由于单元格名称基本上是坐标,所以纯粹是一个算术比较的问题,不需要涉及Excel本身:

 function Test-CellInRange { param( [ValidatePattern('^[AZ]+\d+$')] [string]$Cell, [ValidatePattern('^[AZ]+\d+\:[AZ]+\d+$')] [string]$Range ) # Grab X and Y coordinates from Range input, sort in ascending order (low to high) $P1,$P2 = $Range -split ':' $Xpoints = ($P1 -replace '\d'),($P2 -replace '\d') |Sort-Object $Ypoints = ($P1 -replace '\D'),($P2 -replace '\D') |Sort-Object # Grab X and Y coordinate from cell $CellX = $Cell -replace '\d' $CellY = $Cell -replace '\D' # Test whether cell coordinates are within range return ($CellX -ge $Xpoints[0] -and $CellX -le $Xpoints[1] -and $CellY -ge $Ypoints[0] -and $CellY -le $Ypoints[1]) } 

像这样使用它:

 if(Test-CellInRange -Cell B2 -Range A1:B20){ "B2 is in A1:B20" } 

我不确定COM接口(从来没有使用它),但如果你有INTERSECT方法的访问,那么你可以写这样的东西:

 If Not Application.Intersect(Range("B2"), Range("A1:B20")) Is Nothing Then CODE_IF_TRUE End If 

它只是做了两个范围的交集。 如果它们不相交,那么它肯定不是另一个的子集。 如果您需要检查一个正确的子集,则必须获得更多的创造性,并检查交集是否与整个期望的子集相同。 记住你的设置逻辑,并检查出UNION方法 – 在这些事情之间,你应该能够处理任何你想要的操作。