Excel VBA - 如何从定义的范围中选择多个完整列?

时间:2014-03-20 09:25:34

标签: excel vba excel-vba excel-2010

我想做的事情:

我正在尝试仅根据标题从电子表格中复制某些列。我不是单独复制每个列的循环,而是尝试一次复制多个列。

到目前为止我所拥有的:

With wb.Worksheets("Sheet1")
    Set lasthead1 = .Range("1:1").Find(What:="*", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
    Set headrng1 = .Range("A1", lasthead1)
    For Each c In headrng1
        If Left(c, 1) = "-" Then c = Mid(c, 2, Len(c) - 1)
        If Left(c, 1) = "+" Then c = Mid(c, 2, Len(c) - 1)
    Next c
    Set PRIhead = headrng1.Find(What:="Priority", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set LOGhead = headrng1.Find(What:="Log Date", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set TYPEhead = headrng1.Find(What:="Type", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set CALLhead = headrng1.Find(What:="Call Status", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set DEShead = headrng1.Find(What:="Description", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set IPKhead = headrng1.Find(What:="IPK Status", LookAt:=xlPart, MatchCase:=False, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    .Range(PRIhead, LOGhead, TYPEhead, CALLhead, DEShead, IPKhead).EntireColumn.Copy
End With

问题:

似乎是以下代码行:

.Range(PRIhead, LOGhead, TYPEhead, CALLhead, DEShead, IPKhead).EntireColumn.Copy

我的来源:

我使用This Question上接受的答案将我的代码行放在一起。

1 个答案:

答案 0 :(得分:2)

跟进评论。

问题的原因是因为Range(cell1,[cell2])对象只能接受2个单元格作为参数。

所以你需要使用

wb.Application.Union(PRIhead, LOGhead, TYPEhead, CALLhead, DEShead, IPKhead).EntireColumn.Copy

我使用wb.Application.Union因为(作为评论的后续跟踪),工作簿wb是另一个应用程序对象的一部分。