VBA Loop and copy regions from sheet to sheet - excel

I am trying to loop down the column "Q" on my active sheet, find values that are in between 27 and 40 and then copy that cell along with a region around the cell noted by the (-1, -16) into a new sheet.
Right now I am just making the region bold to make sure that my loop is catching the right values and regions.
I"m new to VBA so if anyone can give me some pointers or advise on how to solve my problem I'd be very appreciative.
Sub Test2()
Application.ScreenUpdating = False
ActiveSheet.Range("Q13").Select
Let x = 0
Do While x < 500
If ActiveCell.Value >= 27 And ActiveCell.Value <= 40 Then
Range(ActiveCell, ActiveCell.Offset(-1, -16)).Select
Selection.Font.Bold = True
ActiveCell.Offset(2, 16).Activate
Else
ActiveCell.Offset(1, 0).Select
End If
x = x + 1
Loop
End Sub

Try below code :
Always set the ScreenUpdating property back to True when your macro
ends.Check this link
Avoid using Select/Activate in your code. Check this link
Always explicitly specify the sheet when working with more than one
sheet.
Avoid using ActiveCell,ActiveSheet and refer to them explicitly.
Sub Test2()
Application.ScreenUpdating = False
Dim lastRow As Long
lastRow = Sheets("sheet1").Range("Q" & Rows.Count).End(xlUp).Row
Dim rng As Range, cell As Range
Set rng = Sheets("sheet1").Range("Q1:Q" & lastRow)
For Each cell In rng
If cell.Value >= 27 And cell.Value <= 40 Then
Sheets("sheet1").Range(cell, cell.Offset(0, -16)).Copy Sheets("sheet2").Cells(Sheets("sheet2").Range("Q" & Rows.Count).End(xlUp).Row + 1, 1)
End If
Next
Application.ScreenUpdating = True
End Sub

Related

Excel VBA If range.value = something then fills Columns G

For example
if range A14:A200
if A14 = 1 so fill G14 Ok
if A14 = 1 so fill G14 Ok
and so on
For example
if range A14:A200
if A14 = 1 so fill G14 Ok
if A15 = 1 so fill G15 Ok
and so on
you could use the excel formulas:
Sub IFSomething()
With Range("A14:A200") reference the needed range
With .Offset(, 6) ' reference the cells 6 columns to the right of referenced range
.FormulaR1C1 = "=IF(RC[-6]=1,""OK"","""")" ' place a formula in referenced range
.Value = .Value ' leave only values
End With
End With
End Sub
So here is revise solution I hope this resolve your query.
Sub If_loop_test()
Dim x As Integer
For x = 1 To 200
If Range("A" & x).Value = 1 Then
Range("G" & x).Value = "ok"
End If
Next
End Sub
Here is a relatively clean and versatile version.
Remember if you're going to be applying this to large data sets this might be slow. you can fix this by importing the range into an array and iterating through that. your code will go from taking 10 seconds on very large data sets to under a second.
Option Explicit
Sub If_Offset_Value()
Dim WS As Worksheet
Dim RG As Range
Dim CL As Range
Dim CheckVal As Variant
' > Change this to whatever value you're checking for.
CheckVal = 1
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Set WS = ThisWorkbook.Worksheets("My WorkSheet Name")
Set RG = WS.Range("A14:A200")
For Each CL In RG.Cells
If CL.Value = CheckVal Then
' > Couple of options here depending on your needs:
' Both options give you the same result, but Offset
' moves left and right if you change RG column,
' whereas column letter referense will stay G
'1) Offset Method
CL.Offset(0, 6).Value = "OK"
'2) Reference Column Letter
WS.Range("G" & CL.Row).Value = "OK"
End If
Next CL
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

My VBA code is not working while using the do while loop

My VBA code below is not looping. Kindly help
Public Sub FunWithLoops()
' Create a loop using Do while loop.
'The aim is to go through a list of numbers down a row, highlight them with a different color if greater than 10.
Dim i As Integer
i = 1
Do While i <= 10
If ActiveCell.Value > 10 Then
ActiveCell.Interior.Color = RGB(255, 0, 0)
'interior changes the background color
End If
ActiveCell.Offset(1, 0).Select
i = i + 10
Loop
End Sub
Just correcting your code without making too many changes you might not be ready to go for:
Public Sub FunWithLoops()
' Create a loop using Do while loop.
'The aim is to go through a list of numbers down a row, highlight them with a different color if greater than 10.
Dim i As Integer
i = 1
Do While i <= 10
If ActiveCell.Value > 10 Then ActiveCell.Interior.Color = RGB(255, 0, 0)
ActiveCell.Offset(1, 0).Select
i = i + 1 ' change this to + "1" not + "10"
Loop
End Sub
Please note that your ActiveCell must always be set BEFORE you run the routine, because there's nothing in the routine to set the ActiveCell first, like a line:
Range("A2").Select
You are checking the value of i against the static value of 10. You then increment i by 10. So the loop executes once, always. You essentially don't have a loop and just some extraneous code as is.
I generally would use a For Loop do go down the rows, as its made for incrementing at set intervals.
Sub FunWithForLoops()
Dim i As Long
Dim lr As Long
With ActiveSheet
lr = .Cells(.Rows.Count, 1).End(xlUp).Row 'Find the last row in Column A
For i = 1 To lr
If .Cells(i, 1).Value > 10 Then 'Test Column A, Row i
.Cells(i, 1).Interior.Color = vbRed 'Modify Column A, Row i
End If
Next i
End With
End Sub
You can do it with a While as well, you just need to increment yourself.
Sub FunWithWhileLoops()
Dim i As Long
Dim lr As Long
With ActiveSheet
lr = .Cells(.Rows.Count, 1).End(xlUp).Row
i = 1
Do While i <= lr
If .Cells(i, 1).Value > 10 Then
.Cells(i, 1).Interior.Color = vbRed
End If
i = i + 1
Loop
End With
End Sub

How to apply a condition to "used range" in whole column as a loop in excel using VBA?

I am beginner at VBA, I am stuck plz help. In this image(linked at the end of paragraph), I am trying to insert line above the cells which contains different name than the name of upper cell. Plz tell me if there is an easier way to do this or how to apply the given if else condition to whole "G" Column...
Still I am adding my code below if you don't need the image...
Sub ScanColumn()
'Application.ScreenUpdating = False
Dim varRange As Range
Dim currentCell As String
Dim upperCell As String
Dim emptyCell As String
currentCell = ActiveCell.Value
bottomCell = ActiveCell.Offset(1, 0).Value
emptyCell = ""
Dim intResult As Integer
intResult = StrComp(bottomCell, currentCell)
Dim emptyResult As Integer
emptyResult = StrComp(currentCell, emptyCell)
'I want to apply below condition to whole G column in used range
If emptyResult = 0 Then
ActiveCell.Select
ElseIf intResult = 0 Then
ActiveCell.Offset(1, 0).Select
Else
ActiveCell.Offset(1).EntireRow.Insert
ActiveCell.Offset(2, 0).Select
End If
End Sub
Here you have, just call the function "evaluateColumn" and pass the parameters, as example the "trial" sub.
Function evaluateColumn(column As String, startRow As Long, wsh As Worksheet)
Dim lastRow As Long
lastRow = wsh.Range(column & wsh.Rows.Count).End(xlUp).Row
Dim i As Long: i = startRow
Do While i < lastRow
If wsh.Cells(i, column).Value <> wsh.Cells(i + 1, column).Value And wsh.Cells(i, column).Value <> "" And wsh.Cells(i + 1, column).Value <> "" Then
wsh.Range(column & i + 1).EntireRow.Insert shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
i = i + 1
lastRow = lastRow + 1
End If
i = i + 1
Loop
End Function
Sub trial()
evaluateColumn "G", 2, ThisWorkbook.Worksheets("Sheet2")
End Sub
As you can see from the difference between my answer and the one below, your question isn't entirely clear. My code is an event procedure. It will run automatically, as you select a cell within the used range of column G.
If the value of the selected cell is the same as the cell below it the next row's cell will be selected.
If there is a value in either of the two cells, a blank row will be inserted and that row's cell selected. (If you want another row enable the row below the insertion.)
If either of the above conditions are true, do nothing and proceed with the selection the user made.
In order to let this code work it must be installed in the code sheet of the worksheet on which you want the action. It will not work if you install it in a standard code module, like Module1.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim TriggerRange As Range
Dim Off As Long ' offset from Target for selection
' if more than one cell is selected choose the first cell
If Target.Cells.CountLarge > 1 Then Set Target = ActiveCell
Set TriggerRange = Range(Cells(2, "G"), Cells(Rows.Count, "G").End(xlUp))
' this code will run only if a cell in this range is selected
' Debug.Print TriggerRange.Address(0, 0)
If Not Application.Intersect(Target, TriggerRange) Is Nothing Then
Application.EnableEvents = False
With Target
If .Value = .Offset(1).Value Then
Off = 1
ElseIf WorksheetFunction.CountA(.Resize(2, 1)) Then
Rows(.Row).Insert
' Off = 1 ' or -1 to change the selection
End If
.Offset(Off).Select
End With
Application.EnableEvents = True
End If
End Sub

Getting error in condition formatting using VBA

I am working on a project in which I am comparing column D with column C of sheet("Backend") and the difference is shown in column E (in %). I'd like to highlight the % difference (column E) in RED color, where the difference is less than -10.00% and greater than 10.00%. Then would like to copy those items from column B corresponding each highlighted cell and paste it in sheet("UPDATER") beneath cell A7.
Attached is the screenshot for your reference
Sub check_date()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wsData As Worksheet, Datasht As Worksheet, lRow As Integer
Set wsData = Sheets("UPDATER")
Set Datasht = Sheets("Backend")
lRow = Datasht.Cells(Rows.Count, 13).End(xlUp).Row
wsData.Range("M8:M" & lRow).Interior.ColorIndex = xlNone
wsData.Range("M8:M" & lRow).FormatConditions.Add Type:=xlExpression, Formula1:="=AND(M8>=EOMONTH(TODAY(),-2)+1,M8<EOMONTH(TODAY(),-1))"
wsData.Range("M8:M" & lRow).FormatConditions(wsData.Range("M8:M" & lRow).FormatConditions.Count).SetFirstPriority
With wsData.Range("M8:M" & lRow).FormatConditions(1).Interior
.Color = RGB(255, 255, 0)
.TintAndShade = 0
End With
wsData.Range("M8:M" & lRow).FormatConditions(1).StopIfTrue = False
Range("M8").Select
End Sub
Here's what I got. It's a bit of a drastic change but I'm hoping this is actually what you're going for.
Sub formatcondition()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim wsData As Worksheet, Datasht As Worksheet, lRow As Integer, My_Range As Range, i As Integer, iRow As Integer, cell As Variant, RowNum As Long, lRowUpdater As Long
Set wsData = Sheets("UPDATER")
Set Datasht = Sheets("Backend")
lRow = Datasht.Cells(Rows.Count, 5).End(xlUp).Row
lRowUpdater = wsData.Cells(Rows.Count, 1).End(xlUp).Row
RowNum = 8 'setting the first row in the UPDATER sheet
Datasht.Range("E1:E" & lRow).Interior.ColorIndex = xlNone 'Reset the color before running
wsData.Range("A8:D" & lRowUpdater + 8).ClearContents 'clear your updater sheet. Remove if not needed.
For i = 1 To lRow
On Error GoTo Continue
If Datasht.Range("E" & i).Value < -0.1 Or Datasht.Range("E" & i).Value > 0.1 Then 'If greater than or less than
Datasht.Range("E" & i).Interior.ColorIndex = 6 'Change the color of affected cells if you need that
wsData.Range(wsData.Cells(RowNum, 1), wsData.Cells(RowNum, 4)).Value = _
Datasht.Range(Datasht.Cells(i, 2), Datasht.Cells(i, 5)).Value 'straight copy the values from the cells as it loops rather than using copy/paste
wsData.Range(wsData.Cells(RowNum, 2), wsData.Cells(RowNum, 4)).NumberFormat = "0.00%" 'change the number format of outputted cells to percentages (if needed)
RowNum = RowNum + 1 'move to the next row in the output
End If
Continue:
Resume Nexti
Nexti:
Next i
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
EDIT:
For the date to add a year my version would be just adding to what I gave earlier. Instead we now add an AND function to contain the OR, then checking if the YEAR in the cell is the current year. If you're only wanting this year then we can also forgo the IF statement which was checking that if the current month was January it would incorporate December. But if thats not needed then:
=AND(OR(MONTH(NOW())=MONTH(M8),MONTH(NOW())-1=MONTH(M8)),YEAR(M8)=YEAR(NOW()))
Or
=AND(MONTH(M8)>=MONTH(NOW())-1,MONTH(M8)<MONTH(NOW())+1,YEAR(M8)=YEAR(NOW()))
Both the same length and do the same thing just in different way.

VBA Change row color based on cell value

I am trying to automate a massive report and one step of the process involves changing the row color based on the value in column B.
Essentially, if B# = "SCC NUPSFTPDE", then I need the row color to be a light blue. (I'm not overly concerned with the exact color TBH).
I've been trying to manipulate code and have basically made my own Frankenstein code so I'm sure it's wrong somewhere in here. Please help!
Dim LastRow As Long
Dim cell As Range
sSheetName = ActiveSheet.Name
With Worksheets(sSheetName)
LastRow = .Cells(.Rows.Count, TEST_COLUMN).End(xlUp).Row
**For Each cell In Range("B2:B" & LastRow)
If cell.Value = "SCC NUPSFTPDE" Then
ColorRow = 39**
Else
cell.EntireRow.Interior.ColorIndex = xlNone
End If
Next
End With
Just to close this question out: change
ColorRow = 39
to
cell.EntireRow.Interior.ColorIndex = 39
or perhaps better, something like
cell.EntireRow.Interior.Color = RGB(129, 218, 239)
You could also try worksheet event - Worksheet_Change which apply the color in every change automatically.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
Dim LastRow As Long
With Me
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
If Not Intersect(Target, .Range("B2:B" & LastRow)) Is Nothing Then
For Each cell In Target
Application.EnableEvents = False
If cell.Value = "SCC NUPSFTPDE" Then
cell.EntireRow.Interior.ColorIndex = 39
Else
cell.EntireRow.Interior.ColorIndex = xlNone
End If
Application.EnableEvents = True
Next cell
End If
End With
End Sub

Resources