Search for text, copy offset rows

强颜欢笑 提交于 2021-01-28 20:48:03

问题


I wrote a macro to read a .csv file. It places the data in Sheet2.

I need to copy a block of data that begins in the row that follows the text string "BP Error". The data that precedes this string can vary in length, but the block of data I'm interested in is of a fixed size. I'd like to copy this block of data into Sheet1.

I tried doing a sub-routine that would search for "BP Error" but I kept getting stuck trying to do Offset copying. I need the next 18 rows of data following that string of "BP Error" (which is always in Column B).

Example: "BP Error" is found in cell B13, copy cells A14:G31 to Sheet1


回答1:


Since you have to find only the first "BP Error", the following code would do the job for you (Dont forget to change the worksheet names and check the ranges to see if they fit your needs):

Sub DoYourJob()

Dim readingRow As Long

Dim sourceSheet As Worksheet
Dim destinationSheet As Worksheet

Set sourceSheet = ThisWorkbook.Worksheets("YourSourceSheetName")
Set destinationSheet = ThisWorkbook.Worksheets("YourDestinationSheetName")

For readingRow = 1 To sourceSheet.Cells(sourceSheet.Rows.Count, 2).End(xlUp).Row

    If sourceSheet.Cells(readingRow, 2) = "BP Error" Then

        sourceSheet.Range(sourceSheet.Cells(readingRow + 1, 1), sourceSheet.Cells(readingRow + 18, 7)).Copy (destinationSheet.Cells(1, 1))
        Exit For

    End If

Next readingRow

End Sub


来源:https://stackoverflow.com/questions/30380659/search-for-text-copy-offset-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!