2016-07-25 68 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 - 在這些事情之間,你應該能夠處理任何你想要的操作。