VBA Loop not working correctly - excel

I am new to writing VBA and not sure to to complete this loop. I am reading down a column and identifying the cell color. If the cell color is correct then i preform the action. The problem is that action pastes that info into cell N7. That is where my loop gets messed up because i need it to go the cell A9 next. Can some one explain what the next step would be. I know that need to put that cell A8 in a loop and increase by 1 each time but not sure how to do that.
Range("A8").Select
Do
If ActiveCell.Interior.Color = RGB(79, 129, 189) Then
ActiveCell.Offset(1, 0).Select
Selection.End(xlDown).Select
ActiveCell.Offset(-1, 0).Select
Range(Selection, Selection.End(xlUp).Offset(1, 0)).Select
Selection.Copy
Range("N7").Select
ActiveSheet.Paste
ElseIf ActiveCell.Select = "BREAK" Then
Exit Sub
Else
ActiveCell.Offset(1, 0).Select
End If
Loop
End Sub

Edit: updated script below to copy data per additional comments
.Select and .Activate are common sources of run-time errors and can likely be avoided in this case. Though I'm not really clear on the action you're trying to take when you identify the color in column A, you could use the following heavily-commented script to accomplish the "loop-and-check-for-BREAK" action.
Option Explicit
Sub ProcessColumnA()
Dim Counter As Long
Dim MySheet As Worksheet
Dim Cell As Range, DestCell As Range
'set references up-front
Counter = 8
Set MySheet = ThisWorkbook.ActiveSheet
Set Cell = MySheet.Cells(Counter, 1)
Set DestCell = MySheet.Cells(7, 14)
'loop on column A until we find "BREAK" or
'counter is greater than 10K, whichever comes first
Do Until Cell.Value = "BREAK" Or Counter > 10000
'check color and take action if necessary
If Cell.Interior.Color = RGB(79, 129, 189) Then
'do the copy work here
Cell.Copy Destination:=DestCell
'increment the destination cell
Set DestCell = DestCell.Offset(1, 0)
End If
'increment the counter variable and set the next cell
Counter = Counter + 1
Set Cell = MySheet.Cells(Counter, 1)
Loop
'send user a message regarding the results
If Counter > 10000 Then
MsgBox ("Whoa you hit 10K cells before finding 'BREAK'...")
Else
MsgBox ("Processing complete!")
End If
End Sub

Related

Excel VBA Moving Row Values [Only] from one Sheet to another - Current code is working, just needs tweaking

This is currently the setup that I have found helpful and have modified to work well... However, I'm struggling with one small further and final modification. I would like to just - Paste Values as opposed to the Formulas.
Sub move_rows_to_another_sheet()
'
Sheets("User").Select
Columns("A:Y").Select
Range("A:Y").Activate
'
For Each myCell In Selection.Columns(25).Cells
If myCell.Value = "Closed" Then
myCell.EntireRow.Copy Worksheets("Archive").Range("A" & Rows.Count).End(3)(2)
myCell.EntireRow.Delete
End If
Next
'
Range("A2").Select
End Sub
''Updated Version - Move Single Rows
'
Sub move_rows_to_another_sheet()
'
Sheets("Users").Select
Columns("A:Y").Select
Range("A:Y").Activate
'
For Each mycell In Selection.Columns(25).Cells
'
If mycell.Value = "Closed" Then
mycell.EntireRow.Copy
Worksheets("Archive").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
mycell.EntireRow.Delete
End If
Next
'
Range("A2").Select
End Sub
The idea is simple... The current code is successful, however, I would like to just copy and paste the [values] of the rows cell content and [not] the formulas etc. The formatting is fine and everything, I just need the result of the functioning formulas recorded.
I have tried various options such as [myCell.EntireRow.CopyValues] even [& Rows.Count & Rows.PasteSpecial]... Any thoughts?
Thanks in advance
I tried your code. It looks like when there are several cells with "closed" it will not work for all. because when one deletes, one should delete from below upwards.
But then the data in Archive is not in right order.
In your original code you can make the range smaller, so it will run faster.
or take what you want from this code:
Sub move_rows_to_another_sheet2()
Dim mycell As Range
Dim checkClosed
Dim Lastrow As Long
Dim i As Long
Set checkClosed = ThisWorkbook.Worksheets("User").Range("Y1:Y10000")
Lastrow = Worksheets("Archive").Cells(Rows.Count, 1).End(xlUp).Row + 1 'one cell below last used cell in column A
For i = 10000 To 1 Step -1 'from row 10000 to row 1
Set mycell = ThisWorkbook.Worksheets("User").Cells(i, "Y")
If LCase(mycell.Value) = "closed" Then 'checks for Closed and closed
mycell.EntireRow.Copy
Worksheets("Archive").Range("A" & Lastrow).PasteSpecial Paste:=xlPasteValues
mycell.EntireRow.Delete
Lastrow = Lastrow + 1
End If
Next i
'
Range("A2").Select
End Sub

Run macro in selected cells

I need to create a simple macro to clean my worksheets. Basically, if there are multiple orders on 1 shipment, I need those orders to be displayed vertically instead of horizontally example:
excel example
I created a macro that will copy/paste the 1st row into the row below it and then change the 2nd order with another copy/paste.
Pretty simple. My problem is the macro is binded to the ranges I created the macro in.
How can I make it so I can run this macro on selected ranges. Rather than manually copy and pasting every row with multiple orders, I'd rather highlight the rows with multiple orders and run the macro.
This is the code:
ActiveCell.Range("A1:M1").Select
Selection.Copy
ActiveCell.Offset(1, 0).Rows("1:1").EntireRow.Select
Selection.Insert Shift:=xlDown
ActiveCell.Offset(0, 3).Range("A1").Select
Application.CutCopyMode = False
Selection.Copy
ActiveCell.Offset(0, -1).Range("A1").Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Range("A1:A2").Select
Application.CutCopyMode = False
Selection.ClearContents
vba code
If I understand you correctly, maybe something like this ?
need those orders to be displayed vertically instead of horizontally
Sub test1()
Dim rg As Range
Dim cc As Range
Set rg = Range("C2")
Do
If rg.Offset(0, 1).Value <> "" Then
Set cc = Range(rg, rg.End(xlToRight))
Rows(rg.Row).Copy
Rows(rg.Row + 1 & ":" & rg.Row + cc.Columns.Count - 1).Insert Shift:=xlDown
rg.Resize(cc.Columns.Count, 1).Value = Application.Transpose(cc)
rg.Offset(0, 1).Resize(cc.Columns.Count, cc.Columns.Count - 1).ClearContents
Set rg = rg.Offset(cc.Columns.Count, 0)
Else
Set rg = rg.Offset(1, 0)
End If
Loop Until rg.Value = ""
End Sub
How can I make it so I can run this macro on selected ranges
Sub test2()
Dim rg As Range
Set rg = Application.InputBox("Select a certain row starts from column C", Type:=8)
Rows(rg.Row).Copy
Rows(rg.Row + 1 & ":" & rg.Row + rg.Columns.Count - 1).Insert Shift:=xlDown
rg.Resize(rg.Columns.Count, 1).Value = Application.Transpose(rg)
rg.Offset(0, 1).Resize(rg.Columns.Count, rg.Columns.Count - 1).ClearContents
End Sub
For sub test1
The code assumed that the delivery number will start in cell C2 which defined as variable rg then do a loop
If the the cell to the right of the rg is not empty,
then it define a range from the rg to the last column of the rg row which has value as cc variable.
Then it copy insert as many as the columns are there inside cc.
Then it transpose the cc value from column to row.
Then it delete the uneeded value.
If the the cell to the right of the rg is empty,
then it doesn't do a process, it just reset the rg to the cell below.
For sub test2
It ask a user to select a range, starts from column C to whatever last column (with value) within the same row. Then do the similar process like in test1.

Do while loop on visible cells only after autofilter?

I am stuck on a code where I apply a filter and then have to copy paste data from filtered rows to another sheet. But for some reason the code is not doing anything at all. I have applied an if condition but that is not working, it would be better if the condition was visible cells condition. Basically I want to apply filter>> then I want to copy cell in column 2 to another worksheet and perform calculation>> then copy calculated value in cell in column 7
Sub DOCFairshare()
Set ws = ThisWorkbook.Sheets("Final Orders") 'Setting worksheet in variable
ws.Activate
ws.AutoFilterMode = False 'Removing all filters
ActiveSheet.Range("$A$2:$EL$1561").AutoFilter Field:=50, Criteria1:= _
"DOC Planning Required" 'DOC Filter applied
i = 1
Do Until IsEmpty(Cells(i, 2))
If Cells(i, 50) = "DOC Planning Required" Then
Cells(i, 7).Copy
Worksheets("DOC Fairshare").Range("A3").PasteSpecial Paste:=xlPasteValues
Sheets("DOC Fairshare").Calculate
Worksheets("DOC Fairshare").Range("D11:U11").Copy
Worksheets("Final Orders").Cells(i, 7).PasteSpecial Paste:=xlPasteValues
Debug.Print Cells(i, 2)
End If
' Debug.Print Cells(i, 2)
i = i + 1
Loop
End Sub
I recommend to look at and use SpecialCells method in VBA help. I think it is very usefull.
In your case using like this example.
Range("A1:A10").SpecialCells(xlCellTypeVisible).Copy Range("C1")
It copies only visible cells to C1 from range A1-A10. I think more elegant then make loop and check if cell is visible and then copy which I used to do.
You do not say anything... I asume that my understanding should be correct. The code also assumes that on the second row there are not headers. If they exist, the line Set rngDocPl = ws.Range("AX2:AX1561")... should be adapted to Set rngDocPl = ws.Range("AX3:AX1561")....
Please, try the next code. It will stop after each iteration and shows in Immediate Window (Ctrl + G being in VBE) the value in G:G before calculations and after. Is it what you need? I cannot imagine what formulas you have in Worksheets("DOC Fairshare") and I cannot test anything:
Sub DOCFairshare()
Dim ws As Worksheet, wsDoc As Worksheet, rngDocPl As Range, cel As Range
Set ws = ThisWorkbook.Sheets("Final Orders") 'Setting worksheet in variable
Set wsDoc = Worksheets("DOC Fairshare") 'is this sheet in the same workbook?
ws.AutoFilterMode = False 'Removing all filters
ws.Range("$A$2:$EL$1561").AutoFilter field:=50, Criteria1:= _
"DOC Planning Required" 'DOC Filter applied
On Error Resume Next
Set rngDocPl = ws.Range("AX2:AX1561").SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If rngDocPl Is Nothing Then MsgBox "No any visible cells in AX:AX column": Exit Sub
For Each cel In rngDocPl.cells
With wsDoc
Debug.Print "before, on row " & cel.row, cel.Offset(0, -43).value 'the cell in G:G before calculations
.Range("A3").value = cel.Offset(0, -43).value 'copy the value from G to "A3"
.Calculate
cel.Offset(0, -43).Resize(1, 19).value = .Range("D11:U11").value 'copy back the calculated range
Debug.Print "after, on row " & cel.row, cel.Offset(0, -43).value: Stop 'the cell in G:G after calculations
End With
Next
End Sub

cell.activate in For Each loop: Run-time error '1004': Activate method of Range class failed

I am attempting a For Each loop using the below code.
Sub child_builder()
Dim cell As Range
For Each cell In ActiveSheet.Range("D5:D102")
If cell.Value = "Y" Then
cell.Activate
Selection.Offset(0, -2).Select
Selection.Copy
Sheets("Child").Select
ActiveSheet.Paste
Selection.Offset(0, 1).Select
ThisWorkbook.Sheets("Product Builder").Activate
Range("G6:I10").Select
Selection.Copy
Sheets("Child").Select
ActiveSheet.Paste
Selection.End(xlDown).Select
Selection.Offset(1, -1).Select
End If
Next cell
End Sub
The first loop works but then fails on the next one due to the line cell.activate.
The error is
Run-time error '1004': Activate method of Range class failed.
Maybe this will get you started, I know its tough to start rewriting the macro recorder stuff. Consider the comments in the code.
Sub child_builder()
Dim cell As Range
Dim RowToPasteTo As Long
RowToPasteTo = 1
For Each cell In ThisWorkbook.Sheets("PutTheNameOfYourSheetHere").Range("D5:D102")
If cell.Value = "Y" Then
'From the cell that has a Y in it, move left 2 columns and copy that to the A1 cell on the sheet "Child". Also consider just assigning a value with = if you dont need formats etc.
cell.Offset(0, -2).Copy ThisWorkbook.Sheets("Child").Range("A" & RowToPasteTo) 'Change the range here if you wanna paste somewhere else
'I am not sure what you are doing now but I assume you want to copy Range G6:I10 from the "Product Builder" sheet just to the right of the value we just copy pasted?
ThisWorkbook.Sheets("Product Builder").Range("G6:I10").Copy ThisWorkbook.Sheets("Child").Range("B" & RowToPasteTo) 'Change the range here if it needs to go somewhere else.
'From what I can tell you want to paste stuff just below what ever you just pasted on the next loop?
RowToPasteTo = RowToPasteTo + 5 'Move down 5 rows (because G6:I10 are 5 rows)
End If
Next
End Sub

End With without With. Not able to loop through columns

So I'm trying to work on a single file, go to each cell in column A on "Source" (from row 1 to last row holding data), place that value in cell C3 on "Destination", recalculate the workbook and save the file
I haven't gotten to save the file yet because I am stuck on looping. Can anybody help please?
Sub test()
Sheets("Source").Select
With ActiveSheet
Set r = Range("Employee #")
For n = 1 To r.Rows.Count
r.Cells(n, 1).Select
Selection.Copy
End With
Sheets("Destination").Select
Range("C3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Next n
End Sub
Started VBA 7 days ago so I am trying to do my best here..
In further review you do not need the with block
Sub test()
with Sheets("Source")
Set r = .Range(.Range("A2"),.Range("A" &.row.count).end(xlup))'Change this to the column you want
end with
For n = 1 To r.Rows.count
r.Cells(n, 1).copy Sheets("Destination").Range("C3")
Application.CutCopyMode = False
Next n
End Sub
or all the slects for that matter. But now you can see that you are putting every value that you loop into one cell.

Resources