如何从一个工作表复制特定列并粘贴到第一行不同范围内的另一个工作表?

时间:2017-05-25 06:41:29

标签: excel vba excel-vba

我是这个vba /宏的新手。我需要复制特定的列并将其粘贴到另一个工作表中。我使用从前一个线程提供的代码。但是,我需要将数据粘贴到第1行。目前,数据粘贴在第2行。以下是代码:

Sub copypaste()

Dim lastrow As Integer, erow As Integer, sheet1 As Worksheet, sheet2 As 
Worksheet, icol As Long

Set sheet1 = Worksheets("Sheet1")
Set sheet2 = Worksheets("Sheet2")
lastrow = sheet1.Cells(Rows.Count, 1).End(xlUp).Row




For i = 4 To lastrow
erow = sheet2.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row
sheet2.Cells(erow, 2) = sheet1.Cells(i, 1)
sheet2.Cells(erow, 3) = sheet1.Cells(i, 2)
sheet2.Cells(erow, 7) = sheet1.Cells(i, 3)
sheet2.Cells(erow, 5) = sheet1.Cells(i, 5)
sheet2.Cells(erow, 4) = sheet1.Cells(i, 6)
sheet2.Cells(erow, 8) = sheet1.Cells(i, 11)
sheet2.Cells(erow, 9) = sheet1.Cells(i, 8)
sheet2.Cells(erow, 13).Value = sheet1.Cells(i, 9).Value
Next i

Worksheets("Sheet1").Columns().AutoFit
Cells(1, 1).Activate

End Sub

也不需要复制sheet1的标题。

感谢。Link from the previous thread. Assistance was given by Tim Wilkinson

@sktneer昨天解决了上述问题。数据已成功粘贴到第1行。

但是,与同一案例相关,如何从sheet1复制过滤后的数据? 我已经输入了自动过滤器代码来指定copypaste过程的标准,但不确定我是否正确完成了它。

以下是经过调整的代码:

sub copypaste()

Dim lastrow As Integer, erow As Integer, sheet1 As Worksheet, sheet2 As 
Worksheet, lrow As Long

Set sheet1 = Worksheets("Sheet1")
Set sheet2 = Worksheets("Sheet2")

strSearch = "LOCAL"
lastrow = sheet1.Cells(Rows.Count, 1).End(xlUp).Row

With sheet1
AutoFilterMode = False
lrow = sheet1.Range("L" & .Rows.Count).End(xlUp).Row

With .Range("L3:L" & lrow)
        .AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"


For i = 4 To lastrow

If sheet2.Cells(1, 2) = "" Then
    erow = 1
Else
erow = sheet2.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row

End If
sheet2.Cells(erow, 2) = sheet1.Cells(i, 1)
sheet2.Cells(erow, 3) = sheet1.Cells(i, 2)
sheet2.Cells(erow, 7) = sheet1.Cells(i, 3)
sheet2.Cells(erow, 5) = sheet1.Cells(i, 5)
sheet2.Cells(erow, 4) = sheet1.Cells(i, 6)
sheet2.Cells(erow, 8) = sheet1.Cells(i, 11)
sheet2.Cells(erow, 9) = sheet1.Cells(i, 8)
sheet2.Cells(erow, 13).Value = sheet1.Cells(i, 9).Value
Next

End With


AutoFilterMode = False

End With


Worksheets("Sheet1").Columns().AutoFit
Cells(1, 1).Activate

End Sub

提前感谢你们。

1 个答案:

答案 0 :(得分:0)

也许这......

transactions.find(regex("note", "(?s).*" + Pattern.quote(s) + ".*", "s"));