如何仅显示具有特定值的列

时间:2014-02-25 20:58:18

标签: excel-vba vba excel

好吧,我是全新的,所以很抱歉侮辱任何人我怀疑是一个简单的问题。然而,我已经搜索并尝试了好几天的事情,并且无法破解坚果 - 我似乎无法完成所有我需要的事情。

这里是: 我有一个工作表,其值每周都会更改。行数和列数也会发生变化。但是,A,B和C列始终具有日期,名称和位置数据,因此必须保留。从D开始的列中的值仅包括数字0,1,2或3。

我需要将列复制到第二个工作表,然后从D向前删除所有没有2或3的列。换句话说,我需要始终保留列A,B和C,并且如果列中的任何位置显示2或3,则还要保留任何列(及其所有数据)。

或者,我敢打赌,选择前三列以及其中包含2或3列的任何其他列会更快,然后将它们粘贴到第二个工作表中。但是,我已经读过关于使用Union的内容,这似乎是要走的路,但它已经超出了我的想象。

提前感谢任何解决方案。

1 个答案:

答案 0 :(得分:0)

我没有看到Union的相关性,所以我希望我没有误解你的要求。

第一项任务是确定最后一行和一列。查找最后一行或列的方法有很多种;这些都不适用于所有情况。我认为SpecialCells在这种情况下最合适。

当我不确定如何实现某些目标时,我将其分解为小任务,编写任务1并使用Debug.Print将诊断信息输出到立即窗口。当我让任务1工作时,我将任务2的代码与新的诊断信息一起添加。所以我的第一个宏Demo1只输出最后一行和一列。尝试将值放在任何现有值的左侧或下方,以查看宏输出的内容。

注意:我对我使用的陈述几乎没有提及。通常,一旦您知道它存在就很容易查找语句。如有必要,请回答问题,但请先尝试自己的调查。

Option Explicit
Sub Demo1()

  Dim ColLast As Long
  Dim RowLast As Long

  ' Replace "Source" with the name of your worksheet
  With Worksheets("Source")

    ColLast = Cells.SpecialCells(xlCellTypeLastCell).Column
    RowLast = Cells.SpecialCells(xlCellTypeLastCell).Row

  End With

  Debug.Print "Last column " & ColLast
  Debug.Print "Last row " & RowLast
  ' Note Cells(RowLast, ColLast) does not have to contain a value.

End Sub

下一个任务是确定要删除的列。我使用工作表函数CountIf来计算从第4列开始的每列中的2和3的数量,即列“D”。

Sub Demo2()

  Dim ColCrnt As Long
  Dim ColLast As Long
  Dim Rng As Range
  Dim RowLast As Long

  With Worksheets("Source")

    ColLast = Cells.SpecialCells(xlCellTypeLastCell).Column
    RowLast = Cells.SpecialCells(xlCellTypeLastCell).Row

    For ColCrnt = 4 To ColLast
      Set Rng = .Range(.Cells(1, ColCrnt), .Cells(RowLast, ColCrnt))
      Debug.Print ColCrnt;
      Debug.Print "  Num 2s=" & WorksheetFunction.CountIf(Rng, 2);
      Debug.Print "  Num 3s=" & WorksheetFunction.CountIf(Rng, 3)
    Next

  End With

End Sub

最后一项任务是删除没有2和3的列。对于Demo2,我使用了For-Loop。 For-Loop的问题是你无法在循环中更改End Value,我们需要在删除列时执行此操作。因此,对于Demo3,我必须使用Do-Loop。

Sub Demo3()

  Dim ColCrnt As Long
  Dim ColLast As Long
  Dim Rng As Range
  Dim RowLast As Long

  With Worksheets("Source")

    ColLast = Cells.SpecialCells(xlCellTypeLastCell).Column
    RowLast = Cells.SpecialCells(xlCellTypeLastCell).Row

    ColCrnt = 4
    Do While ColCrnt <= ColLast
      Set Rng = .Range(.Cells(1, ColCrnt), .Cells(RowLast, ColCrnt))
      If WorksheetFunction.CountIf(Rng, 2) + _
         WorksheetFunction.CountIf(Rng, 3) > 0 Then
        ' This column contains a 2 or a 3.  Do not delete column.
        ' Advance to next column
        ColCrnt = ColCrnt + 1
      Else
        ' This column does not contain a 2 or 3.  Delete column.
        .Columns(ColCrnt).EntireColumn.Delete
        ' Reduce ColLast to allow for deletion.
        ColLast = ColLast - 1
      End If
    Loop

  End With

End Sub

希望以上有所帮助。

相关问题