Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations cowski on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBA Code Debug

Status
Not open for further replies.

dagonet

Computer
Mar 26, 2008
3
So it's probably obvious that I am a newbie by looking at my code. Why doesn't this work? What should I do to fix?

In this example I use the Excel Formula in C3 =CountA(Sheet2!A:A), which returns the value of 11 (number of rows not empty), which includes Headers.
I want to copy the Range on Sheet2 (A2:F11) because the count told me 11 rows to Sheet1 (A2:F11)

Dim MyCount = Integer
Dim i = Integer

Sub do_it()

MyCount = Sheets("Sheet1").Cells(C, 3)

For i = 2 To MyCount
Sheets("Sheet1").Cells(A, i) = Sheets("Sheet2").Cells(A, i)
Sheets("Sheet1").Cells(B, i) = Sheets("Sheet2").Cells(B, i)
Sheets("Sheet1").Cells(C, i) = Sheets("Sheet2").Cells(C, i)
Sheets("Sheet1").Cells(D, i) = Sheets("Sheet2").Cells(D, i)
Sheets("Sheet1").Cells(E, i) = Sheets("Sheet2").Cells(E, i)
Sheets("Sheet1").Cells(F, i) = Sheets("Sheet2").Cells(F, i)
Next i

End Sub
 
Replies continue below

Recommended for you

When referring to cell "A1" using the .Cells property, you should use Cells(1,1), not Cells(A,1). Also, with .Cells, the row number comes first. So cell "C2" is Cells(2, 3).

-handleman, CSWP (The new, easy test)
 
try
sheets("sheet1").range("A2:F11").value = sheets("sheet2").range("A2:F11").value
 
Thank you for your help. Both of your solutions helped point be in the right direction. I was missing one critical component to the MyCount variable.

MyCount = Sheets("Sheet1").Cells(C, 3).value

the MyCount varialbe was not getting the value of cell C3 so the loop was never functional. Here is the code that solved my problem.

Dim i As Integer
Dim MyCount As Integer

Sub do_it()

MyCount = Cells(1, 3).Value

For i = 2 To MyCount
Sheets("Sheet1").Cells(i, 1) = Sheets("Sheet2").Cells(i, 1)
Sheets("Sheet1").Cells(i, 2) = Sheets("Sheet2").Cells(i, 2)
Sheets("Sheet1").Cells(i, 3) = Sheets("Sheet2").Cells(i, 3)
Sheets("Sheet1").Cells(i, 4) = Sheets("Sheet2").Cells(i, 4)
Sheets("Sheet1").Cells(i, 5) = Sheets("Sheet2").Cells(i, 5)
Sheets("Sheet1").Cells(i, 6) = Sheets("Sheet2").Cells(i, 6)
Next i


End Sub

Thanks again.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor