Uploaded by parva thamma

macro example

advertisement
‘ macro for EXCEl sheet data copy
Sub ReadAndWriteRows()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim lastRow As Long
Dim maxX As Double
Dim maxC As Double
Dim maxD As Double
Dim i As Long
Dim j As Long
Dim k As Long
Dim lRowC As Long
Dim lRowD As Long
'set reference to worksheets
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
'get last row in sheet1
lastRow = ws1.Cells(Rows.Count, 1).End(xlUp).Row
'get values for maxX, maxC, and maxD
maxX = ws1.Cells(lastRow, 5).Value
maxC = Application.WorksheetFunction.Max(ws1.Range("C1:C" & lastRow))
maxD = Application.WorksheetFunction.Max(ws1.Range("D1:D" & lastRow))
'write header row to sheet2
For i = 1 To 10
ws2.Cells(1, i).Value = ws1.Cells(1, i).Value
ws2.Cells(1, i).Font.Color = vbBlue
Next i
'loop through rows in column C, find max and min values in subrange, and write to sheet2
lRowC = ws1.Cells(Rows.Count, 3).End(xlUp).Row
For j = lastRow To 2 Step -1
If ws1.Cells(j, 3).Value >= (maxC * 0.01 * maxX) And ws1.Cells(j, 3).Value <= (0.95 * maxC) Then
lRowC = lRowC + 1
For k = 1 To 10
ws2.Cells(lRowC, k).Value = ws1.Cells(j, k).Value
ws2.Cells(lRowC, k).Font.Color = vbBlue
Next k
End If
Next j
'loop through rows in column D, find max and min values in subrange, and write to sheet2
lRowD = ws1.Cells(Rows.Count, 4).End(xlUp).Row
For j = lastRow To 2 Step -1
If ws1.Cells(j, 4).Value >= (maxD * 0.01 * maxX) And ws1.Cells(j, 4).Value <= (0.95 * maxD) Then
lRowD = lRowD + 1
For k = 1 To 10
ws2.Cells(lRowD, k).Value = ws1.Cells(j, k).Value
ws2.Cells(lRowD, k).Font.Color = vbRed
Next k
End If
Next j
End Sub
Download