简体   繁体   中英

Paste to next empty column

I already have this code that paste to the next empty row. It works perfectly but now I have a new VBA project that i would like to do the same thing but columns instead of rows

Current Code:

 intLast = shtAlpha.Cells(Rows.Count, "C").End(xlUp)
 intNext = intLast + 5 - (intLast + 1) Mod 5
 Set rngDest = shtAlpha.Cells(intNext, "C").Resize(5, 3)

I tried this but I got Compile Error Method or data member not found , It highlights

.Cells

/

intLast = Omega.Cells(Columns.Count, "1").End(xlRight).Column
intNext = intLast + 5 - (intLast + 5) Mod 5
Set rngDest = Omega.Cells(intNext, "A").Resize(30000, 3)

The Range() function accepts only cell references as text Strings eg Range("A1") .

The Cells() function accepts only numeric row/column references eg Cells(1, 1) .

In this case, you'd need to change

 intLast = shtAlpha.Cells(Rows.Count, "C").End(xlUp)

to

 intLast = shtAlpha.Cells(Rows.Count, 3).End(xlUp)

To get the last column in row 1 with anything in it you should be doing

intLast = Omega.Cells(1,Omega.Columns.Count).End(xlToLeft).Column
intNext = intLast + 5 - (intLast + 5) Mod 5
Set rngDest = Omega.Cells(1,intNext).Resize(30000, 3)

Let's go through the changes one at a time:

Cells takes two parameters. The first indicates the row the second indicates the column. You want to start on the last column of the first row . So the first parameter should be 1. The second should be the number of columns in your worksheet.

Note that it is generally a good practice to specify which worksheet/workbook you are working on. This helps prevent errors if there are multiple books open or the wrong worksheet is selected.

.End will take you to the boundary of the region you are in. Since you are at the last cell on the first row you are at the far-right of the sheet. So you have tomove to the left to find the last column with values in it. hence .End(xlToLeft)

Note The documentation tells us that the parameter must be one of these values.

Now for your error message. You can often refer to this handy VBA error list for more info on what could be causing your error. I reccomend searching the error number if it is given in the error alert.

It sounds like your error is caused because Omega is not the correct type. VBA is telling you that you are trying to access a member called Cells but it cannot find it in the object. I suggest adding Omega to the watch and look at its members when the error occurs. With a little debugging you should be able to find the source of the problem!

Hopefully this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM