例如,我在寻找,确定以下逻辑:确定是否细胞在规定范围内存瓦特/ Powershell的Excel的COM
if (B2 in A1:B20) # if cell B2 is within the range A1:B20
{
return $true
}
有没有在Excel的功能,可用于这样的事情?我读了about = COUNTIF()函数,但无法使其工作。再次,这是使用PowerShell中的Excel COM对象。
感谢
例如,我在寻找,确定以下逻辑:确定是否细胞在规定范围内存瓦特/ Powershell的Excel的COM
if (B2 in A1:B20) # if cell B2 is within the range A1:B20
{
return $true
}
有没有在Excel的功能,可用于这样的事情?我读了about = 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 - 在这些事情之间,你应该能够处理任何你想要的操作。
感谢您的支持!你能举一个例子说明你如何调用这个函数吗?我在理解正则表达式时遇到了一些问题 – Quanda
@Quanda增加了一个例子! ValidatePattern属性只是确保Cell坐标总是正确的格式(即'[一个或多个字母] [一个或多个数字]')。 –
它的工作非常好,谢谢! @Mathias R. Jessen – Quanda