2017-04-17 100 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