使用Powershell Excel COM确定指定区域中是否存在单元格



例如,我希望确定以下逻辑:

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

excel中有没有一个函数可以用于类似的事情?我读过关于=COUNTIF()函数的文章,但没能让它正常工作。同样,这是在Powershell中使用ExcelCOM对象。

感谢

由于单元格名称基本上是坐标,这纯粹是一个算术比较的问题,不需要涉及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方法,那么你可以写这样的东西:

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

它只是做两个范围的集合交集。如果它们不相交,那么其中一个绝对不是另一个的子集。如果你需要检查一个合适的子集,你必须更有创意,检查交集是否与整个期望的子集相同。记住您的集合逻辑并检查UNION方法——在这两者之间,您应该能够处理任何类型的操作。

最新更新