【发布时间】:2019-01-22 21:06:33
【问题描述】:
我试图弄清楚如何使用RANGE() 和CELLS() 选择多个不连续的范围。
我的工作表(Sheet5)看起来像这样:
| A | B | C | D | E | F |
+---+---+---+--------+---+-----------+
1|...|...|...|Category|...|Description|
2|...|...|...|Apple |...|Fruit |
3|...|...|...|Carrot |...|Vegetable |
4|...|...|...|Hat |...|Clothing |
- 我想将
Category列和Description列设置为可以复制并粘贴到另一个文件的范围。 - 列标题在第一行。
- 我要查找的列当前位于
Column D和Column F,但它们可能会移动。 - 这两列是不连续的范围,例如,我不想选择
Column E中的任何内容。
到目前为止,我的代码找到了Category 列、Description 列和lastrow。当我使用变量来选择范围时,我使用的是Range() 和Cells()。
我的代码:
Sub SelectNonContiguousRangeCells()
'Create variables
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim lastrow As Long
Dim strCat As String
Dim strDesc As String
Dim rngCat As Range
Dim rngDesc As Range
Dim rngCopy As Range
'Initialize variables
Set wb = ThisWorkbook
Set ws = Sheet5
lastrow = ws.Range("A1").End(xlDown).Row
'Find the column headers
strCat = "Category New"
strDesc = "Requirement Description"
Set rngCat = ws.Range("A1:Z1").Find(strCat)
Set rngDesc = ws.Range("A1:Z1").Find(strDesc)
'Set the copy range
Set rngCopy = Range(Range(Cells(1, rngCat.Column), Cells(lastrow, rngCat.Column)), Range(Cells(1, rngDesc.Column), Cells(lastrow, rngDesc.Column))).SpecialCells(xlCellTypeVisible)
Debug.Print rngCopy.Address
End Sub
在我的Debug.Print 中返回的范围是$D$1:$F$449,这是一个连续的范围,而我希望看到$D$1:$D$449,$F$1:$F$449,这是一个非连续的范围。
我查看了this answer 并找到了一些有用的信息,但它似乎对非连续范围没有帮助。
我也一直在浏览 MSDN 上的 Range.Cells documentation,但没有运气。
如何使用我的变量来选择包含 Category 和 Description 的列,而两者之间没有任何内容?
【问题讨论】: