宏用于复制具有固定列的可变行数

时间:2015-03-03 10:36:04

标签: excel-vba vba excel

我在互联网上搜索得很高,以找到我的宏观问题的答案 - 我不认为我想要的是那么困难,但也许就是这样!

在我的数据集列中,K包含我的数据标记。我想要做的是在列K中找到“22”并找到“23”是列K并复制列C到J中的所有行数据,这些行落在由列K中包含的标记指示的行号之间。标记22和23之间的行对于每个电子表格是不同的,这是我遇到问题的地方。我试图设置这些变量的范围,但我基本上是一个宏观新手,并没有太多的运气。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

可能最简单的方法就是找到22& 23并确定行所在的位置

然后,您可以创建要使用这些已知行和列进行复制的范围。 为工作表命名"复制到工作表"对于这个例子。

Sub Button1_Click()
    Dim Rws As Long, Rng As Range
    Dim c1 As String, c2 As String
    Dim FndC1 As Range, FndC2 As Range
    Dim c1C As Integer, c2C As Integer
    Dim ws As Worksheet
    Set ws = Sheets("Copy to Sheet")
    c1 = 22
    c2 = 23
    Rws = Cells(Rows.Count, "K").End(xlUp).Row
    Set Rng = Range(Cells(1, "K"), Cells(Rws, "K"))

    Set FndC1 = Rng.Find(what:=c1, lookat:=xlWhole)
    Set FndC2 = Rng.Find(what:=c2, lookat:=xlWhole)

    If Not FndC1 Is Nothing Then
        c1C = FndC1.Row
    Else: MsgBox c1 & " Not Found"
        Exit Sub
    End If
    If Not FndC2 Is Nothing Then
        c2C = FndC2.Row
    Else: MsgBox c2 & " Not Found"
        Exit Sub
    End If
    Range(Cells(c1C + 1, "C"), Cells(c2C - 1, "J")).Copy _
            ws.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)


End Sub
相关问题