VBA如何粘贴几列的行?

时间:2017-10-17 17:49:04

标签: vba excel-vba excel

这是我目前的代码,基于这个答案:https://stackoverflow.com/a/11633207

我的代码目前将复制的代码粘贴在Sheet2的底部,从A列开始。如何创建它以便从C列开始复制行?

Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim lastRow As Long
Dim strSearch As String
Dim i As Integer

Set ws1 = Worksheets("Sheet1")

With ws1
    .AutoFilterMode = False
    lRow = .Range("J" & .Rows.Count).End(xlUp).Row

    With .Range("J1:J" & lRow)
        strSearch = "John"
        .AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
        Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With


    Set ws2 = Worksheets("Sheet2")
    With ws2
        lastRow = ws2.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
        copyFrom.Copy .Rows(lastRow + 1)

    End With

    .AutoFilterMode = False
End With

3 个答案:

答案 0 :(得分:1)

您可以更好地编写此代码,无需复制整行并粘贴它。这将限制您,但只是为了轻松解决您的问题替换此行:

copyFrom.Copy .Rows(lastRow + 1)

用这个:

 Set Rng = copyFrom.SpecialCells(xlCellTypeConstants)
 Rng.Copy .Cells(lastRow + 1, 3)

请注意,3代表C列,您实际上可以将其更改为您想要的任何列。

答案 1 :(得分:0)

快速执行此操作的方法是仍然复制/粘贴整行,但要删除目标端行的前两列,向左移动:

copyFrom.Copy .Rows(lastRow + 1) 'As before.

'Edit:

'If you meant to pull the pasted data towards the left:
.Range(.Cells(lastRow + 1, 1), .Cells(lastRow + GetRowsInRange(copyFrom), 2)).Delete Shift:=XlDeleteShiftDirection.xlShiftToLeft

'If you meant to push the pasted data towards the right:
.Range(.Cells(lastRow + 1, 1), .Cells(lastRow + GetRowsInRange(copyFrom), 2)).Insert Shift:=XlInsertShiftDirection.xlShiftToRight

编辑:您必须计算已复制的行数。

Public Function GetNumRowsInRange(ByVal prngFullRows As Excel.Range) As Long
    Dim result As Long
    Dim rngArea As Excel.Range

    For Each rngArea In prngFullRows.Areas
        result = result + rngArea.Rows.Count
    Next

    GetNumRowsInRange = result
End Function

答案 2 :(得分:-1)

设置偏移量以移动到3列,即C:

Set copyFrom = .Offset(1, 3).SpecialCells(xlCellTypeVisible).EntireRow

如果这适用于您,请尝试