简体   繁体   English

复制列中具有特定文本的行 VBA Excel

[英]Copy rows with specific text in a column VBA Excel

I am very new to VBA and all coding so I'm not very good at even the basics yet.我对 VBA 和所有编码都很陌生,所以我什至还不太擅长基础知识。

I have a worksheet in excel with about a dozen different business' Balance Sheets.我在 excel 中有一张工作表,其中包含大约十几个不同企业的资产负债表。 I need to copy all of the the rows in a specific range based on the Asset name in column D. The specific range I need to copy is in between "Securities" and "Derivatives."我需要根据 D 列中的资产名称复制特定范围内的所有行。我需要复制的特定范围介于“证券”和“衍生品”之间。

I successfully copied all the lines of data in between the first set of "Securities" and "Derivatives" but my For Loop keeps copying the same first range when I need it to move to the next set of "Securities" and "Derivatives" Data.我成功地复制了第一组“证券”和“衍生品”之间的所有数据行,但是当我需要它移动到下一组“证券”和“衍生品”数据时,我的 For 循环不断复制相同的第一个范围.

I have tried and thought maybe adding a variable to my rngA might work?我试过并认为可能向我的 rngA 添加一个变量可能有效吗? Any help is appreciated.任何帮助表示赞赏。

'''
    
Sub ChartReference2()
    Dim findrow As Long

    Dim findrow2 As Long
    Dim rngA As Range
    
    
    For Each cell In ActiveWorkbook.Worksheets("BS growth").Range("A:A")
        If cell.Value = "Asset" Then
            Worksheets("BS growth").Activate
            findrow = Range("D:D").Find("Securities", Range("D3")).Row
            findrow2 = Range("D:D").Find("Derivatives", Range("D" & findrow)).Row
            Range("D" & findrow & ":D" & findrow2, Selection.End(xlToRight)).Select
            Selection.Copy
    
    End If
    Next cell
    
    
    End Sub

'''

Try this - comments in-line试试这个 - 在线评论

Sub ChartReference2()
    
    Dim ws As Worksheet, assetRow, f1 As Range, f2 As Range
    
    Set ws = ActiveWorkbook.Worksheets("BS growth")
    
    assetRow = Application.Match("Asset", ws.Columns("A"), 0)
    If Not IsError(assetRow) Then 'matched a cell in Col A?
        With ws.Columns("D")
            Set f1 = .Find("Securities", lookat:=xlWhole, after:=.Cells(assetRow - 1), _
                            SearchDirection:=xlNext)
            If Not f1 Is Nothing Then      'found the value?
                Set f2 = .Find("Derivatives", lookat:=xlWhole, after:=f1, _
                                SearchDirection:=xlNext)
                If Not f2 Is Nothing Then  'found the value?
                    ws.Range(f1, f2).Copy  'copy range
                End If
            End If
        End With
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM