2016-07-25 71 views

回答

1

由于单元名称基本上坐标,这是纯粹的算术比较的问题,没有必要到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" 
} 
+0

感谢您的支持!你能举一个例子说明你如何调用这个函数吗?我在理解正则表达式时遇到了一些问题 – Quanda

+0

@Quanda增加了一个例子! ValidatePattern属性只是确保Cell坐标总是正确的格式(即'[一个或多个字母] [一个或多个数字]')。 –

+0

它的工作非常好,谢谢! @Mathias R. Jessen – Quanda

1

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

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

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