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

Determine if cell exists in a specified range w/ Powershell Excel COM

例如,我要确定以下逻辑:

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

excel 中是否有函数可用于此类目的?我阅读了有关 =COUNTIF() 函数的信息,但无法使其正常工作。同样,这是在 Powershell 中使用 Excel COM 对象。

谢谢

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

function Test-CellInRange
{
    param(
        [ValidatePattern('^[A-Z]+\d+$')]
        [string]$Cell,
        [ValidatePattern('^[A-Z]+\d+\:[A-Z]+\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 Method 那么您可以这样写:

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

它只是做两个范围的交集。如果它们不相交,那么一个绝对不是另一个的子集。如果您需要检查一个适当的子集,您必须更有创意并检查交集是否与整个所需子集相同。记住你的设置逻辑并检查 UNION Method - 在这些事情之间你应该能够处理你想要的任何类型的操作。