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.
Related
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.
I see this question asked and answered but I'm missing something! In order to use Named Ranges in my VBA I must activate the sheet before using the Named Range, otherwise it accesses the "same" range in the active sheet. I have:
made sure that the named range scope is set to Workbook.
fully qualified every range and cell method or property in my code
Here is the code. It works fine if I put back in the worksheet.activate call but otherwise it references a range in the wrong sheet (the active one).
Sub UserForm_Initialize()
' Application.ScreenUpdating = False
Dim r1 As Long, c1 As Long, r2 As Long, c2 As Long, rng1 As Range, rng2 As Range, s As Worksheet, initSheet As Worksheet
Set s = Sheets("NamePlates")
Set rng1 = s.Range("MasterStoreNamePlates")
Set initSheet = Application.ActiveSheet
r1 = rng1.Row
c1 = rng1.Column
r2 = r1 + storeCount - 1
c2 = c1
's.Activate
With s
listBoxStores.RowSource = .Range(.Cells(r1, c1), .Cells(r2, c2)).Address
End With
'initSheet.Activate
' Application.ScreenUpdating = True
End Sub
It's not too demanding to switch to a different sheet for a quick range lookup, but come on... what's the point of naming the ranges and making the name global and all the posts about "make sure to set the name to global" if I have to still go and switch the active sheet?
Thanks in advance!
An update:
Sub UserForm_Initialize()
Application.ScreenUpdating = False
Dim rng1 As Range, rng2 As Range, sInd As Long, initSheet As Worksheet, s As Worksheet
sInd = Sheets("NamePlates").index
Set s = Sheets(sInd)
Set rng1 = s.Range("NamePlates!MasterStoreNamePlates")
Set initSheet = Application.ActiveSheet
listBoxStores.RowSource = rng1.Range(s.Cells(1, 1), s.Cells(storeCount - 1, 1)).Address
Application.ScreenUpdating = True
End Sub
Doesn't provide any different result. It still accesses the active sheet. If I change the active sheet before doing this, it retrieves the right data, otherwise it pulls the range from the active sheet.
I noticed that s.Range("NamePlates!MasterStoreNamePlates") does get me the correct range... but then when I use that range and do something relative to it, I lose the sheet reference. So I think maybe my solution will involve dynamically updating the named range and then this method should work. Currently you can see that I'm using that constant "storeCount" which is not really a very good way to do things. It is just kind of my hack for getting things up and running. All the other suggested methods fail in my case for the same reason; even if they make a good reference to the correct range, I loose that sheet reference when I start doing anything that defines the range I want, which is 12 rows longer than the named range (thus the "storeCount" constant).
If I can't figure out how to do a dynamically changing named range I'll post a new question but I've seen some things about that so I should be able to get that working and I'll post my solution here... or if someone beats me to it I'll accept that answer even though it's a little different from the OP.
ThisWorkbook.Names("NamedRange").RefersToRange
This will return the range object of the named range.
i am adding another answer as the original question was modified significantly. it looks to me that you are over-complicating a matter which is rather simple if you understand it.
Before i explain further, i think your approach with setting the ".RowSource" with the ".address" property of a range is incorrect because the address property does not contain a reference of the parent sheet so it will always refer to the active sheet even if you have gotten that address from a global wb range. see below:
i hope the below would be helpful to you to achieve what you want. No ranges! No activations! keep it simple. i have been working with vba 12 years and i can count in one hand the number of times i have used .activate & .select
I have initialized my form with 3 list boxes (i) static hardcoded range (ii) named range and (iii) dynamic named range.
Private Sub UserForm_Initialize()
Dim addr1 As String
Dim addr2 As String
Dim addr3 As String
addr1 = "LB!$A$1:$A$4"
addr2 = "List.Items" ' named range defined as "=LB!$A$1:$A$3"
addr3 = "List.Items.Dyn" ' dynamic named range defined as "=OFFSET(LB!$A$1,0,0,COUNTA(LB!$A:$A),1)"
Me.testListBox1.RowSource = addr1
Me.testListBox2.RowSource = addr2
Me.testListBox3.RowSource = addr3
Debug.Print Me.testListBox1.RowSource
Debug.Print Me.testListBox2.RowSource
Debug.Print Me.testListBox3.RowSource
End Sub
here is the Debug.Print result in the immediate window
In my user form i have three listboxes populated from the same cells but referenced differently in the .RowSource property. It also works regardless which is the active sheet.
here i am initializing the same form from another worksheet
why do you want to activate the sheets when you could possibly do:
listBoxStores.RowSource = s.Range(s.Cells(r1, c1), s.Cells(r2, c2)).Address
instead of:
With s
listBoxStores.RowSource = .Range(.Cells(r1, c1), .Cells(r2, c2)).Address
End With
I am trying to copy specific cells in a range from sheet1 to specific cells in sheet2.
However, when I simply use .PasteSpecial data gets overwritten. This is because the range from sheet1 is not always the same size and could cause it to overwrite data on sheet2. I want to paste the data from sheet1 on sheet2 but if the range is bigger on sheet1 than on sheet2 it has to first insert rows on sheet2 so it does not overwrite other data.
Here is some some example code for what I've tried (I am not experienced in VBA so excuse me for any weird code):
Sub ResizeNamedRange()
Dim xWb As Workbook
Dim xNameString As String
Dim xName As Name
Dim row_count As Integer
Set xWb = Application.ActiveWorkbook
xNameString = "Destination_A"
Set xName = xWb.Names.Item(xNameString)
Set row_count = xWb.Names.Item(xNameString).Rows.Count
If row_count <= 1 Then
Sheets("Hours").range("A9:E14").PasteSpecial xlPasteValues
End If
End Sub
However I keep getting errors like Object required and others. Does anyone know how to do this? I appreciate all the help I can get!
Two initial tips - use Set statement only when assigning value to a variable or a property. See:
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/set-statement
Additionally, you cannot use Rows.Count on Names.Item. Instead, you can replace it with:
xNameString = "Destination_A"
Set xName = xWb.Names.Item(xNameString)
row_count = Range(xName.RefersTo).Rows.Count
I have data in Excel. I want to copy the header and some data from the middle of sheet to Powerpoint. I know that you can't copy a selection of non-adjacent cells in Excel, but I was under the impression it would work with VBA.
My try:
With Workbooks(1).Sheets(1)
Set rng = Union(.Range("B2:K3"), .Range("B45:K85"))
End With
I can select "rng", but I can't paste it anywhere because I get the error message that you can't paste non-adjacent cells.
I've also tried this, but it resulted in the whole table (B2:K85) getting copied:
With ThisWorkbook.Sheets("Sheet1")
Set rng1 = .Range("B2:K3")
Set rng2 = .Range("B45:K85")
Set NewRng = .Range(rng1.Address & ":" & rng2.Address)
End With
I've googled this question and tried various things, but either I misunderstood what is possible with VBA or I'm making a mistake (over and over again).
So do I have to alter my code or do I have to work around it? My alternative solution would be to copy-paste each of the two ranges, put them underneath each other and then copy the whole, now contiguous range.
You can use the Areas property of the Range object to get the unionized ranges. Code like the below will loop through each of the sub-ranges, copy them, and paste them elsewhere. Try and adapt to your needs, and write back if you need some help.
Sub Test()
Dim rng As Range
Dim r As Range
Dim destination As Range
Set rng = Union(Range("A1:B3"), Range("D1:E2"))
Set destination = Range("H1")
For Each r In rng.Areas
r.Copy destination
Set destination = destination.Offset(, 3)
Next r
End Sub
So I am trying to use the autofill method in vba right now over a range that is set to a variable. I know that the range of cells you are autofilling from must be included in the destination. So, I do just that. However, and much to my surprise, all the cells in the range are being set to nothing.
Here is the code:
Dim table2Range As Range
Dim table2Range2 As Range
Dim table2Range3 As Range
Dim tableholder As Range
Set table2Range2 = Range("Y54").End(xlToRight).Offset(0, 1)
Set table2Range3 = Range("Y77").End(xlToRight).Offset(0, 1)
Set table2Range = Range(table2Range2, table2Range3)
Set tableholder = Range("y54", table2Range3)
tableholder.Select
table2Range.AutoFill Destination:=Selection 'This is setting all my cells to nothing for some reason
Here is the before & after screenshots:Before, After
Any help is hugely appreciated!
Your AutoFill line of code should be:
SourceRange.AutoFill Destination:FillRange
It seems like your "table2Range " is the source, which overlap with your Fill Range. I.e:
.End(xlToRight).Offset(0, 1) will set range from Y54 to the rightmost cell of the same row.
You can edit the source range with hardcode first (i.e. Range("Y54:Z77") and see if that works for you, then work from there
For example (try on a new workbook):
Sub example()
Set SourceRange = Worksheets("Sheet1").Range("A1:B1")
Set fillRange = Worksheets("Sheet1").Range("A1:G1")
SourceRange.AutoFill Destination:=fillRange
End Sub
Enter "1" in cell(A1) and "2" in Cell(B1) and run the code.