简体   繁体   中英

Excel VBA programming to copy specific rows from sheet1 to sheet2 specific cell

I want to write one vba code which will search data from a specific column of sheet1 and copy those rows and paste those to sheet2. I have written the code but found one problem there. here is the code below.

    Sheets("Sheet1").Select
    Range("D1").Select
    Dim mycode As Worksheet
    Set mycode = ThisWorkbook.Worksheets("Sheet2")
    Dim i As Long
    For i = 2 To Cells(Rows.Count, "D").End(xlUp).Row
        If Cells(i, 4).Value = "high" Then
            Range(Cells(i, 1), Cells(i, 8)).Copy Destination:=mycode.Range("A" & mycode.Cells(Rows.Count, "A").End(xlUp).Row + 1)
            ElseIf Cells(i, 4).Value <> "high" Then
            Sheets("Sheet2").Select
            Range("A2").Value = "No Crtical Logs Found"
            End If
        Next i
    End Sub

From sheet1 column D(number4) I am searching data matching "high" and copy paste those rows to sheet2. And if any of the "high" is not there in column D then "No action required" will be written in cell A2 on sheet2. But the problem is when "high" value is not there it is working fine but when "high" value is there in D column sheet1 then all time "no action required" value is coming on cell A2 on sheet2. Please help me to rectify this.

No Crtical Logs Found   4/11/2016   Critical    high        192.168.1.1 This is the sample excel sheet  Action Required

Regards, Pinaki

You are moving off Sheet1 too soon:

Sub fhskdfh()
    Sheets("Sheet1").Select
    Range("D1").Select
    Dim mycode As Worksheet
    Set mycode = ThisWorkbook.Worksheets("Sheet2")
    Dim i As Long
    For i = 2 To Cells(Rows.Count, "D").End(xlUp).Row
        MsgBox i & vbCrLf & Cells(i, 4).Value
        If Cells(i, 4).Value = "high" Then
            Range(Cells(i, 1), Cells(i, 8)).Copy Destination:=mycode.Range("A" & mycode.Cells(Rows.Count, "A").End(xlUp).Row + 1)
        End If
    Next i
End Sub

Change your destination of the "No Crtical Logs Found" message
From

Sheets("Sheet2").Select Range("A2").Value


To

Sheets("Sheet2").Range("A2").Value

You do not need to select the cell before assigning a value to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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