在excel中查找两个数组(两个范围)之间的并集,并显示它们共有的值

时间:2015-08-21 12:38:47

标签: arrays excel vba unions

好的,所以这个有点超出了我的范围,我无法找到任何这方面的例子(我搜索了Google,Stack,MSDN和几个论坛)。

让我们假设Array1由范围A1中的值组成:A3一个Sheet16(一列但三行)。该数组包含值1,2,3
让我们假设Array2由范围A1:C1中的值组成;值1,2和3(一行但3列)。

我如何看到下面的图片,找到两个数组之间的联合,然后隐藏表17中所有不在两个数组(集合)的并集内的列。

换句话说,如何隐藏工作表17中的A列和C列(因为范围B1包含两个数组之间的并集,即" 2"。

我知道我可以按如下方式建立两个阵列,我只是不确定从哪里开始:

Sub Array_123()

Dim myarray As Variant, myarray2 As Variant

myarray = Application.Transpose(ThisWorkbook.Worksheets("sheet16").Range("a1:a3").value)
myarray2 = Application.Transpose(ThisWorkbook.Worksheets("sheet17").Range("a1:c1").value)

End Sub

请看下面,非常感谢任何帮助!!谢谢!

enter image description here

2 个答案:

答案 0 :(得分:0)

不是我写的最好的,但做了我理解你想要的

  1. 探索Sheet17的列列表
  2. 当在Sheet16的值列表中找到列标题时,保持可见,否则隐藏(排名不再相关)

    Private Sub hideUnmatchCol()
    
        Dim col As Integer
        Dim rc As Variant
    
        col = 1
    
        Do Until Worksheets("Sheet17").Cells(1, col).Value = ""
    
           On Error Resume Next
           rc = ""
           rc = Worksheets("Sheet16").Columns("A:A").Find(What:=Worksheets("Sheet17").Cells(1, col).Value, _
                After:=Worksheets("Sheet16").Cells(1, 1),  LookIn:=xlFormulas, LookAt _
                :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
                False, SearchFormat:=False).Address
           If rc = "" Then
              Worksheets("Sheet17").Columns(col).EntireColumn.Hidden = True
           Else
              Worksheets("Sheet17").Columns(col).EntireColumn.Hidden = False
           End If
           On Error GoTo 0
           col = col + 1
        Loop
    
    End Sub
    
  3. 希望有所帮助

答案 1 :(得分:0)

如果我正确理解了问题,你试图使用表16的值作为表17中列的索引。如果索引匹配,则column.hidden == False,否则column.hidden == True。

现在,可以使用以下方法轻松完成此任务。

子测试()

Dim myarray As Variant, myarray2 As Variant

'sheet 2 is dictating what happens with the columns on sheet one

myarray = Worksheets("Sheet1").Range("a1:d1") '2 dimentional array
myarray2 = Worksheets("Sheet2").Range("a1:a4") '2 dimentional array

'check if the arrays are of the same length. We are comparing the rows of one to the columns of the other
If (UBound(myarray2, 1) = UBound(myarray, 2)) Then 'if row length of one is the same as column length of the other
    For arrayIndex = 1 To UBound(myarray2, 1) 'for loop based on the length of the elements in the array
        If (myarray(1, arrayIndex) = myarray2(arrayIndex, 1)) Then 'if the elements at each index point in the arrays have a matching value hide the column
            Worksheets("Sheet1").Columns(arrayIndex).Hidden = True
        End If
    Next arrayIndex
End If

End Sub