Home > database >  Looping and copying with the right condition - first time coding :(
Looping and copying with the right condition - first time coding :(

Time:09-30

I'm a complete beginner with VBA (coding generally) so apologies in advance with terrible coding below - I'm trying to loop copy from one sheet to another sheet, with the condition that the cell it copies to is dependent on the right column next to it not being empty. If empty then the loop should stop.

Updated the code to the following:

Public Sub emptycell()

Dim Conditionalcol As Integer     'this is dependant on the 'column' of names
Conditionalcol = 4
 
Dim Projectrow As Integer         'row empty for project name
Projectrow = 4

Dim Projectdowncell As String     'move down cell for project name pasting
Projectdowncell = 1

Dim projectcellright As Integer   'move  cell right 1 down for project name copying
projectcellright = 5


Do While Sheets("Datacopied").Cells(Conditionalcol, 3) <> "" 'this is the condition to stop at empty cell
 a = Cells(Conditionalcol, 1)
 'copy and paste as per below'
 Sheets("Dataneeded").Cells(projectcellright, 2) _
.Copy Destination:=Sheets("datacopied").Range("B3") _
.Offset(Projectdowncell, 0)

 Projectdowncell = Projectdowncell   1
 projectcellright = projectcellright   1
 Conditionalcol = Conditionalcol   1
 
Loop
End Sub

When the condition is met, it correctly stops, however I want it to copy the cell the same number of times of rows in column C, up until the cell is blank. instead it copies test 1 to 4 with respect to A1 to A4. Any help please? [1]: let's say this is the data. And name of the sheet is data

On the same workbook the other sheet's name is copy. This sheet is where we transfer the data.

First thing, i will count the number of the rows on data page. then i will transfer the data from data page to copy page

Sub copy()
Dim i As Long
Dim ws_data As Worksheet
Dim ws_copy As Worksheet
Dim num_of_rows As Long

Set ws_data = ThisWorkbook.Worksheets("data")
Set ws_copy = ThisWorkbook.Worksheets("copy")



' Here I am counting number of the rows in data page
i = 1
Do While ws_data.Cells(i, 1) <> ""
i = i   1
Loop

num_of_rows = i - 1

MsgBox (num_of_rows)


'and i will transfer the data from data page to copy page


For i = 1 To num_of_rows

ws_copy.Cells(i, 1) = ws_data.Cells(i, 1)
ws_copy.Cells(i, 2) = ws_data.Cells(i, 2)
Next i


End Sub
  • Related