Excel VBA:根据行和列标题复制和粘贴选择

时间:2016-05-25 16:06:08

标签: excel vba excel-vba

我正在尝试创建一个将格式化并创建每周报告的宏。 它有五列需要移动:密钥,摘要,创建,状态,修复版本。

我需要复制从Key列的第2行开始并在Fix Version / s列的最后一行结束的选择,然后将其粘贴到名为“Priority Issues”的工作表中。我不确定如何编码这个特定的选择。

我需要将最后一行存储在变量中,因为最后一行可能会在每周更改。本质上,我正在寻找允许我从第2行和Key列的交叉点到最后一行和Fix Version / s列的交集进行选择的代码,但我不确定如何做到这一点。

Function FindCol(toFind As String) As Range
Dim Rtn As Range
Set Rtn = Rows(1).Find(What:=toFind, LookIn:=xlValues, _
          LookAt:=xlWhole, MatchCase:=True)
Set FindCol = Rtn
End Function

Sub Move_Severity()
Dim Severity As Range
Dim Key As Range
Dim Fix_Version As Range
Dim LastRow As Long

Set Severity = FindCol("Severity")
Set Key = FindCol("Key")
Set Fix_Version = FindCol("Fix Version/s")
LastRow = Cells(Rows.Count, Severity.Column).End(xlUp).Row

'This is where I am running into problems
Range(Cells(2, Key), Cells(LastRow, Fix_Version)).Copy
Sheets("Priority Issues").Range("A2").Paste
End Sub

1 个答案:

答案 0 :(得分:1)

Sub Move_Severity()
Dim Severity As Range
Dim Key As Range
Dim Fix_Version As Range
Dim LastRow As Long

Set Severity = FindCol("Severity")
Set Key = FindCol("Key")
Set Fix_Version = FindCol("Fix Version/s")

With ActiveSheet '<~~ change active sheet reference to whatever must it be 
    .Range(.Cells(2, Key.Column), .Cells(.Rows.Count, Severity.Column).End(xlUp)).Copy Destination:=Sheets("Priority Issues").Range("A2")
End With

End Sub

如果您只需要粘贴值,然后将With-End With部分更改为

With ActiveSheet
    With .Range(.Cells(2, Key.Column), .Cells(.Rows.Count, Severity.Column).End(xlUp))
        Sheets("Priority Issues").Range("A2").Resize(.Rows.Count, .Columns.Count).Value = .Value
    End With
End With

更快