i have this test dataset:
i have it on multiple sheets, but its always different range - more columns, more rows etc. Beneath this "header" are always some blank rows.
I would like to loop throug all sheets and select this header using End(xlDown) and End(xlToRight).
I am trying to do this with the following code:
Sub WorksheetLoop()
Dim ws As Worksheet
Dim rng As Range
For Each ws In ActiveWorkbook.Worksheets
Set rng = Range("A1", Range("A1").End(xlDown).End(xlToRight))
rng.Delete
Next ws
End Sub
This macro deletes everything on first worksheet and nothing happens on any other sheet.
I tried using ws.rng but then i get an object error.
Can you please tell me what am i doing wrong?
I am studying some VBA material and trying to make changes, but i always end up with an error.
Thanks
This error is very common.
You must add a sheet reference to every instance of Range (and Cells) as otherwise your range can be straddling two sheets (the specified one and the active sheet, which is implied in the absence of anything else), which causes an error.
Set rng = ws.Range("A1", ws.Range("A1").End(xlDown).End(xlToRight))
In this particular case, you could also consider this variation:
Set rng = ws.Range("A1").currentregion
CurrentRegion.
Related
The following VBA code (Excel 2007) is failing with Error 1004, "Autofill Method of Range Class Failed.". Can anyone tell me how to fix it?
Dim src As Range, out As Range, wks As Worksheet
Set wks = Me
Set out = wks.Range("B:U")
Set src = wks.Range("A6")
src.AutoFill Destination:=out
(note: I have Googled, etc. for this. It comes up fairly often, but all of the responses that I saw had to do with malformed range addresses, which AFAIK is not my problem.
At someone's suggestion I tried replacing the autofill line with the following:
src.Copy out
This had the effect of throwing my Excel session into an apparent infinite loop consuming 100% CPU and then just hanging forever.
OK, apparently the source has to be part of the destination range for autofill. So my code now looks like this:
Dim src As Range, out As Range, wks As Worksheet
Set wks = Me
Set out = wks.Range("B1")
Set src = wks.Range("A6")
src.Copy out
Set out = wks.Range("B:U")
Set src = wks.Range("B1")
src.AutoFill Destination:=out, Type:=xlFillCopy
Same error on the last line.
From MSDN:
The destination must include the
source range.
B:U does not contain A6 and thus there is an error. I believe that you probably want out to be set to A6:U6.
Specifiying just the column name means that you want to fill every row in that column which is unlikely to be the desired behvaiour
Update
Further to the OP's comment below and update to the original answer, this might do the trick:
Dim src As Range, out As Range, wks As Worksheet
Set wks = Me
Set out = wks.Range("B1")
Set src = wks.Range("A6")
src.Copy out
Set out = wks.Range("B1:U1")
Set src = wks.Range("B1")
src.AutoFill Destination:=out, Type:=xlFillCopy
Set out = wks.Range("B:U")
Set src = wks.Range("B1:U1")
src.AutoFill Destination:=out, Type:=xlFillCopy
AutoFill is constrained to a single direction (i.e. horizontal or vertical) at once. To fill a two-dimensional area from a single cell you first have to auto-fill a line along one edge of that area and then stretch that line across the area
For the specific case of copying the formatting and clearing the contents (by virtue of the source cell being empty), this is better:
Dim src As Range, out As Range, wks As Worksheet
Set wks = Sheet1
Set out = wks.Range("B:U")
Set src = wks.Range("A6")
src.Copy out
To make AutoFill work, you need to make the range of AutoFill more than the source range. If the AutoFill range is same as of Source range then there is nothing to AutoFill in that range and hence you would get an error
1004: AutoFill method of Range class failed.
So make AutoFill range more than the source range and error will gone.
If you want to autofill you just do something like...
Private Sub Autofill()
'Select the cell which has the value you want to autofill
Range("Q2").Select
'Do an autofill down to the amount of values returned by the update
Selection.AutoFill Destination:=Range("Q2:Q10")
End Sub
This would autofill down to the specified range.
Does ths help?
Not sure if this helps anyone, but I needed something similar. Selecting the cells as destination works;
dim rowcount as integer
Sheets("IssueTemplate").Select ' Whatever your sheet is
rowcount = 0
rowcount = Application.CountA(Range("A:A"))'get end range
Cells(4, 3).Select 'select the start cell
'autofill to rowcount
Selection.AutoFill Destination:=Range("C4:C" & rowcount), Type:=xlFillDefault
in my example I had to auto-generate a list of folder names from OA100 to OA###?, and this worked fine.
I am trying to copy values from one workbook and paste them into another using the cells property of the range object. How do I properly state range references so that I am not receiving a '1004' runtime error?
I'm working on Excel 2013, and I am running the code in "Practicebook" workbook with an active worksheet.
I've researched many similar problems like this one, Run time error 1004 in Range(Cells()), but they have not helped me. I've made sure my references are fully qualified.
Sub Transfer()
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Set wsCopy = Workbooks("Practicebook2").Worksheets("Sheet1")
Set wsDest = Workbooks("Practicebook").ActiveSheet
wsCopy.Range(wsCopy.Cells(2,8)).Copy
wsDest.Range("J5").PasteSpecial
End Sub
When I run the code, error message "Method 'Range' of object'_Worksheet' failed" appears, with the 6th line of code pasted below highlighted by the debugger. When changing the reference to A1 style notation, the code produces the pasted value in the destination sheet as expected.
Range expects a string or TWO cells to define the range.
With only one CELL remove the RANGE:
wsCopy.Cells(2,8).Copy
When using two cells it would be something like this:
wsCopy.Range(wsCopy.Cells(2,8),wsCopy.Cells(4,10)).Copy
If instead you have the range desired as a string in the the cell one would need to append .Value to the Cells()
wsCopy.Range(wsCopy.Cells(2,8).Value).Copy
Now it will take the value in that cell as a string an pass it to the Range.
Also skip the dual lines:
wsCopy.Cells(2,8).Copy wsDest.Range("J5")
Copy takes an argument of the destination.
Two things you can consider when working with ranges:
1- You can refer to sheets by their code names and this prevents an error if someone changes their name in Excel
2- You don't need to use the cells inside a range. So code could look like this:
Sub Transfer()
'Dim wsCopy As Worksheet -> Don't need this if you refer to the sheet with it's codename
Dim wsDest As Worksheet
'Set wsCopy = ThisWorkbook.Worksheets("Sheet1") -> Don't need this if you refer to the sheet with it's codename
Set wsDest = ThisWorkbook.ActiveSheet
Sheet1.Cells(2, 8).Copy wsDest.Range("J5") ' -> Refer directly to source sheet codename
End Sub
I am using this code to set a range of filtered table to visible cells only.
Set rngMyRange = Selection.SpecialCells(xlCellTypeVisible)
However, there is a strange bug if only one cell is selected, that is, the code selects all used range in the filtered table.
If the selection is greater than one cell, then the code works as expected. Is there a way around this?
Usually using "Selection" is not a good practice; I am guessing you just need to get the range of the visible cells for that you can easily use this:
Sub GetVisibleRangeOnly()
Dim tbl As ListObject
Dim rng As Range
'change the name of the table and worksheet as you need
Set tbl = Worksheets("Sheet1").ListObjects("Table1")
'Note: if there is no visible cell after filtraton rng IS NOTHING will be TRUE
Set rng = tbl.DataBodyRange.SpecialCells(xlCellTypeVisible)
End Sub
Hi I have the following code, the first part of which works fine, but I cannot get the destination bit for rng2 to work - keep getting a "application-defined or object-defined error". Wondered if anyone could help with where I am going wrong as I've tried a few different methods (destination being the neatest I know a little about).
Sub Assign_TN()
' Assign_TN Macro
Dim ws As Worksheet
Dim wbk2 As Workbook
Dim ws2 As Worksheet
Dim Rng As Range
Dim rng2 As Range
Set ws = ThisWorkbook.Worksheets("Check sheet")
Set wbk2 = Workbooks.Open("A Location\TNG Register ongoing.xlsx")
Set ws2 = wbk2.Worksheets("TNG")
'This clears the TN has failed comment in the event the cannot generate Tn macro has been run
ws.Range("A83").ClearContents
' Copy the first set of data from the checksheet and paste into the first blank row of the TNG register
Set Rng = ws.Range("B93:M93")
Rng.Copy Destination:=ws2.Cells(Rows.Count, 2).End(xlUp).Offset(1)
'copy second set of data from checksheet and paste into first blank cell in column 22
Set rng2 = ws.Range("Q93:AM93")
rng2.Copy
Destination = ws2.Cells(Rows.Count, 22).End(x1Up).Offset(0)
All I need this to do is copy two ranges data into two separate area's of the first unpopulated row in a second sheet. This in effect generates an acceptance number which is subsequently copied and pasted into the first sheet (this bit of code hasn't been added and works well).
How can i modify the code below to select data from any worksheets and copy they to another worksheet for example select and copy data from Worksheets("uno") and paste they to Worksheets("duo"). Because the code below selects data only on activesheet
Set tbl = ActiveCell.CurrentRegion
tbl.Resize(tbl.Rows.Count, tbl.Columns.Count).Select
I have a code to copy data from any sheet to another for example
Worksheets("uno").Range("A5:T5,A7:T56,W5,Y5,W7:W56,Y7:Y56").Copy _
Worksheets("duo").Range("B4")
But i want to copy a range with data and ignore blank cells because the range A5:T5 it doesn't have always all cells with data concretely the last cells of this range, two or three of those, and also the same on range A7:T56.
My problem is how to select a range with data and ignore the blank cells inside the range A7:T56 concretely the last rows and the last columns which haves blank cells
Well, for the first part, where "the code selects data only on the activesheet", you just need to activate the correct sheet (for example: "Worksheets("uno").Activate") before executing "Set tbl = ActiveCell.CurrentRegion".
I am not really sure if I understand you correctly, but these are my thoughts:
If you don't want to activate worksheet "uno" you need to create a reference to that worksheet to have a direct access to it:
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Application.Workbooks("<name of your workbook>")
Set wks = wkb.Worksheets("uno")
If you now use the following code:
wks.Range("<your range>").Copy
you have just copied your selected cells, now you can paste it wherever you want.
As for the part with avoiding empty cells:
Generally speaking, you need to create a method of checking whether relevant cells are empty or not before you add them to your range.
Personally, I would avoid trying to copy the whole range as such. Instead I would:
1) loop through all relevant cells in your range one by one
2) for each cell check if it's empty
3) if empty, go to next cell
4) if not empty, copy that cell and paste to the target worksheet
5) jump to next relevant cell
6) when you reach the cell which is just after your last cell, quit looping
I would use the above defined wks object.
Note that a Range object can be treated as a collection of strings, so you can iterate using For... Next loop (For Each loop does not guarantee the index order).
Something like this should do:
Dim rng As Range
Set rng = wks.Range("<your range>")
Dim numOfItems As Integer, itm, i As Integer
numOfItems = rng.Count
For i = 1 To numOfItems
itm = rng.item(i)
If itm <> "" Then
'set value of the corresponding cell in your target worksheet to itm
'<relevant cell>.Value = itm
Else
'do nothing
End If
Next i
I hope it's at least a little bit helpful.