2017-04-17 97 views
0

我有一個腳本(感謝SO的幫助!),以允許用戶選擇一些不連續的列並將其索引插入到數組中。我現在需要做的是有效地選擇剩餘的列,即用戶不是選擇到另一個數組中,以對這些列執行單獨的操作。Excel有效地找到剩餘的列

例如,用戶選擇列A,C,F,G,並將這些索引放入數組Usr_col()中。剩下的列(B,D,E)需要存儲在數組中rem_col()

現在我所能想到的就是測試用戶選擇列的每個用過的列的索引,如果它不包含在該數組中,請將其插入到一個新數組中。就像這樣:

For i = 1 to ws.cells(1, columns.count).end(xltoright).column 
    if isinarray(i, Usr_col()) = false Then 
     rem_col(n) = i 
     n = n+1 
    end if 
next 

我只是尋找一個更有效的解決方案。

+1

如果當前代碼有效,這可能更適合[CodeReview](https://codereview.stackexchange.com/)。 –

+0

確保在'columns.count'之前添加'ws.',否則它將計算任何活動頁面上的列。 – BruceWayne

回答

0

我同意@ScottHoltzman這個網站通常不會成爲使工作代碼更高效的舞臺。但是,這個問題對你之前的問題提出了不同的看法,因爲最明顯的解決方案是在一個循環中將列號分配給一個或另一個數組。

下面的代碼爲您提供了一個框架示例。您需要檢查用戶選擇的正確列。另外,在循環中重新規劃一個數組並不是很好的形式,但是如果用戶選擇了相鄰的列,那麼你需要獲取區域數量和列數以獲得數組大小。如果在你的環形罐內進行重新渲染,我將把它留給你:

Dim targetCols As Range, allCols As Range 
Dim selColNum() As Long, unselColNum() As Long 
Dim selIndex As Long, unselIndex As Long 

Set targetCols = Application.InputBox("Select your columns", Type:=8) 

For Each allCols In Sheet1.UsedRange.Columns 
    If Intersect(allCols, targetCols) Is Nothing Then 
     ReDim Preserve unselColNum(unselIndex) 
     unselColNum(unselIndex) = allCols.Column 
     unselIndex = unselIndex + 1 
    Else 
     ReDim Preserve selColNum(selIndex) 
     selColNum(selIndex) = allCols.Column 
     selIndex = selIndex + 1 
    End If 
Next