Attempt to reference a sheet yields "Run Time Error 1004" - vba

I'm just trying to select a column so that I can change the date format. I have no idea why, but my code is giving me a huge issue anytime I try to reference the sheet the column is in. But what I don't understand is that many times earlier in my code I successfully reference the sheet with no issues.
Has anyone seen this?
Did VBA just forget about me defining and setting my variable?
Here's an example of my code:
Dim wbPrescrub As Workbook, wsPrescrub As Worksheet
Set wbPrescrub = ThisWorkbook
Set wsPrescrub = wbPrescrub.Sheets("PreScrub")
wsPrescrub.Range("A1").AutoFilter Field:=5, Criteria1:=(""), _
Operator:=xlFilterValues
wsPrescrub.Range("E2:E" & pslastRow).SpecialCells (xlCellTypeBlanks).EntireRow.Delete
wsPrescrub.AutoFilterMode = False
wsPrescrub.Columns("F:F").EntireColumn.AutoFit
wsPrescrub.Columns("F:F").Select
Selection.NumberFormat = "mm/dd/yyyy"
I included lines of my code which worked fine, it is the last two lines that are giving me trouble. I cannot get past the wsPrescrub.Columns line. If I run the code without referencing the sheet it works perfectly fine on the ActiveSheet and correctly selects the column and format. But the second I add in what sheet to look at I get:
Run Time Error 1004: Application-defined or object defined error

Related

ChangePivotCache giving type mismatch error

I have a macro that previously reset the cache of two pivot tables without any error. I'm running into a run time error 13 type mismatch for just 1 of the tables and I do not understand why it's suddenly not working. And for just the one table as well when the code is identical for both tables.
Sub refresh_caches()
Dim cpt As PivotTable, chpt As PivotTable
Set ca2 = Sheets("claim edit").Range("A2")
Set cha2 = Sheets("chrg review").Range("A2")
Set cpc = Range(ca2.End(xlToRight), ca2.End(xlDown))
Set chpc = Range(cha2.End(xlToRight), cha2.End(xlDown))
Set cpt = Sheets("Formulas & Pivots").PivotTables("ptClaim")
Set chpt = Sheets("Formulas & Pivots").PivotTables("ptCharge")
cpt.ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
cpc, Version:=xlPivotTableVersion15)
chpt.ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
chpc, Version:=xlPivotTableVersion15)
For Each PivotCache In ActiveWorkbook.PivotCaches
PivotCache.Refresh
Next
End Sub
The run time error is hitting on the changepivotcache code. When I step through and skip to the second code for chpt, it updates that table fine.
Any help would be greatly appreciated.
Edit The error appears after the data source, which is a data connection, is refreshed. I get the same error even when referencing the range directly as the sourcedata. Though if i manually change the data source the pivot table updates just fine.
Whats also odd that when referencing the full range of data directly it will throw the error, but if I do not reference every row it will update the table.
NEW Edit I believe I've identified the line causing my issue, though I do not fully understand why or if this is what caused the issue previously. I narrowed the issue down to the exact cell and it seems to happen whenever any cell in the range contains more than 255 characters. I tested this with additional cells in the range by adding text to the cell and prompted the error, likewise I could prevent the error by ensuring the text of the cell contained no more than 255 chars.
Why is this? I can manually select the data range and use it as my pivotcache but I cannot get the code to do the exact same thing. Found some issues with cells exceeding 255 chars on google but am still baffled as I'm not referencing the cell specifically, just including it in a range. Would really appreciate some insight on this, especially so I can find a workaround for the next time the data pulls a cell value exceeding this limit.
Although I still do not fully understand why the code errors out whenever a cell containing over 255 characters are included in the data range, it does appear to be the cause.
I've implemented a bit of code to simply identify the cells and reduce the text down to the acceptable amount before setting the PivotCache.
Dim c as Range
For each c in Range("SpecialtyClaimEdit") 'the name of my data connection
If Len(c) > 255 Then
c = Left(c, 255)
End If
Next
It seems that excel has a limit of 255 characters for some properties for some reason.
For instance, I was trying to set descriptions for my UDFs (user-defined functions) and I found out that it is limited to 255 characters. Here's my question: Error while setting UDF description in VBA
Also, if you try to write a function with more than 255 characters in one cell excel cannot handle it. Look at this thread: Excel: Use formula longer that 255 characters
What you have now as an answer works but also you need to loop over all of the cells and loose/remove some of the data. I think, it may also work to make a new sheet and refer to the cells in your original sheet (e.g in cell A1 of the new sheet you type ='Formulas & Pivots'!A1). Then, use that sheet in your code. You need to take the address of the pivot table range from the original sheet and then set another range which is the same but in the new sheet.

VBA Runtime error 1004 when trying to access range of sheet

I am building a small vba script that is merging tables from several workbook into one single worksheet of another workbook. The error is raised when I try to set the destination range's value:
wksPivotData.Range(wksPivotData.Cells(CurrentRow, 1)).Resize(tbl.ListRows.Count, tbl.ListColumns.Count).Value = _
tbl.Range.Value
The error: "Run-time error '1004': Application-Defined or object-defined error"
I went through similar questions, and the general answer is what I found in this one: The selected cell belongs to another worksheet than the one desired.
While this makes complete sense, I still can't figure why my code breaks as I'm only using numerical reference (CurrentRow is a Long) and Resize, which should prevent me from doing such a mistake.
Additionally, I ran a couple quick tests in the Immediate window and it turns out that while the worksheet wksPivotData exists and I can access its name and a cell value, the range function simply doesn't work:
Debug.Print wksPivotData.Name
PivotData
Debug.Print wksPivotData.Cells(1, 1).Value
123
Both of those work but the next one doesn't:
Debug.Print wksPivotData.Range(1, 1).Value
Your last line, Debug.Print wksPivotData.Range(1, 1).Value won't print because you're misuing Range(). I assume you want A1?
When using Range(1,1), you're referring to a non-existent range. If you want to do cell A1, you need
With wksPivotData
myData = .Range(.Cells(1,1),.Cells(1,1)).Value
End with
Since you're using multiple worksheets, I'd use the with statement as above. Another way to write the same thing is wksPivotData.Range(wksPivotData.Cells(1,1),wksPivotData.Cells(1,1)) (You need to explicitly tell Excel what sheet you want to refer to when using Range() and cells().
Finally, for your resize, if I recall correctly, you're going to have to add the same Cell() twice in your range:
wksPivotData.Range(wksPivotData.Cells(CurrentRow, 1),ksPivotData.Cells(CurrentRow, 1)).Resize(tbl.ListRows.Count, tbl.ListColumns.Count).Value = _
tbl.Range.Value
Or, for the same thing, but different way of doing it:
With wksPivotData
.Range(.Cells(currentRow, 1), .Cells(currentRow, 1)).Resize(tbl.ListedRows.Count, tbl.ListColumns.Count).Value = tbl.Range.Value
End With

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

I have an Excel document that copies a template sheet into a new sheet on the first time it runs. Any more sheets that follow this template are appended to the newly created sheet.
I'm getting the error in the title in this section of code:
If Worksheets("User Configuration").Cells(9, 15).Value = 1 Then
Worksheets("Cable Cards Template").Range("A1:J33").Copy
With Worksheets("Cable Cards")
**.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues**
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlFormats
End With
Worksheets("Cable Cards Template").Shapes("Picture 1").Copy
Worksheets("Cable Cards").Paste Cells(RangeStartRow, RangeStartColumn)
Call Sheets.FormatCableCardRows
End If
Basically if the If statement is true (the cell = 1), then a range on a particular sheet should be copied and pasted into the new sheet at the range given using PasteSpecial for values and formatting. Following that, the "newly created" sheet should have an image copied into the top left cell of the template and then a subroutine is called to format the rows of the new sheet.
I'm getting the error at the first .Range call after the With Worksheets("Cable Cards") statement. I've tried not using the With statement, copying values directly instead of paste-special etc. The weird thing is that this will run on the first go, when the new sheet is created via:
If (RangeStartRow = 1) Then
Worksheets.Add().Name = "Cable Cards" ' Create new sheet with given name only on first cable card
Columns(1).ColumnWidth = 9.43
Columns(6).ColumnWidth = 11
Columns(10).ColumnWidth = 9
Call FormatForA5Printing("Cable Cards", 71)
End If
but on the 2nd go, it fails entirely, with the Run Time Error 1004 'Application Defined or Object Defined Error'. I'd appreciate any help.
Your cells object is not fully qualified. You need to add a DOT before the cells object. For example
With Worksheets("Cable Cards")
.Range(.Cells(RangeStartRow, RangeStartColumn), _
.Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
Similarly, fully qualify all your Cells object.
Solution #1:
Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards") prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn) (e.g.) gives you a Range, that would be ok, and that is why you often see Cells used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet. Thus, your code attempts using .Range(rng1, rng2), where .Range is a method of one Worksheet object and rng1 and rng2 are in a different Worksheet.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards") prior to executing your Sub and it will start working (now you have well-formed references to Ranges). For the code you posted, adding .Activate right after With... would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range in another Worksheet.
With a sheet other than Worksheets("Cable Cards") active, set a breakpoint at the line throwing the error, start your Sub, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells or Range without a specified object (e.g., Worksheet, or Range) might be dangerous, especially when working with more than one Sheet, unless one is quite sure about what Sheet is active.
Assgining a value that starts with a "=" will kick in formula evaluation and gave in my case the above mentioned error #1004. Prepending it with a space was the ticket for me.

Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class

In my macro, I have the following code :
i = Application.WorksheetFunction.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)
where 'str_accrual' is a string captured earlier to this line and the Range selected is in a single row say from "A1" to "BH1" and the result will be a number which is the position of that string in that range selected.
When I run the macro, I get the error:
Run time error '1004' Unable to get the Match propertyof the WorksheetFunction class
But when I run the macro line by line using (F8) key, I don't get this error but when I run the macro continuously I get the error. Again, if the abort the macro and run it again the error doesn't appear.
I tried several times. It seems that if there is no match, the expression will prompt this error
if you want to catch the error, use Application.Match instead
Then you can wrap it with isError
tons of posts on this error but no solution as far as I read the posts. It seems that for various worksheet functions to work, the worksheet must be active/visible. (That's at least my latest finding after my Match() was working randomly for spurious reasons.)
I hoped the mystery was solved, though activating worksheets for this kind of lookup action was a pain and costs a few CPU cycles.
So I played around with syntax variations and it turned out that the code started to work after I removed the underscore line breaks, regardless of the worksheet being displayed. <- well, for some reason I still had to activate the worksheet :-(
'does not work
'Set oCllHeader = ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, _
Application.Match( _
strValue, _
ActiveWorkbook.Worksheets("Auswertung").Range( _
oCllSpielID, _
ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, lastUsedCellInRow(oCllSpielID).Column)), _
0))
'does work (removed the line breaks with underscore for readibility) <- this syntax stopped working later, no way around activating the worksheet :-(
Set oCllHeader = ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, Application.Match(strValue, ActiveWorkbook.Worksheets("Auswertung").Range(oCllSpielID, ActiveWorkbook.Worksheets("Auswertung").Cells(oCllSpielID.Row, lastUsedCellInRow(oCllSpielID).Column)), 0))
In the end I am fretting running into more realizations of this mystery and spending lots of time again.
cheers
I was getting this error intermittently. Turns out, it happened when I had a different worksheet active.
As the docs for Range say,
When it's used without an object qualifier (an object to the left of the period), the Range property returns a range on the active sheet.
So, to fix the error you add a qualifier:
Sheet1.Range
I had this issue using a third-party generated xls file that the program was pulling from. When I changed the export from the third-party program to xls (data only) it resolved my issue. So for some of you, maybe there is an issue with pulling data from a cell that isn't just a clean value.
I apologize if my nomenclature isn't great, just a novice to this.
That is what you get if MATCH fails to find the value.
Try this instead:
If Not IsError(Application.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)) Then
i = Application.Match(str_accrual, Range(Selection, Selection.End(xlToRight)), 0)
Else
'do something if no match is found
End If
Update
Here is better code that does not rely on Selection except as a means of user-input for defining the range to be searched.
Sub Test()
Dim str_accrual As String
Dim rngToSearch As Range
str_accrual = InputBox("Search for?")
Set rngToSearch = Range(Selection, Selection.End(xlToRight))
If Not IsError(Application.Match(str_accrual, rngToSearch, 0)) Then
i = Application.Match(str_accrual, rngToSearch, 0)
MsgBox i
Else
MsgBox "no match is found in range(" & rngToSearch.Address & ")."
End If
End Sub
I used "If Not IsError" and the error kept showing. To prevent the error, add the following line as well:
On Local Error Resume Next
when nothing is found, Match returns data type Error, which is different from a number. You may want to try this.
dim result variant
result = Application.Match(....)
if Iserror(result)
then not found
else do your normal thing

Subscript out of range Error after renaming sheets

I have done a small project, which consists of 5 excel sheet in, code is working fine and I am getting exact result also, but if I rename sheets from sheet1 to some other name I am getting Subscript out of range Error.
What is the reason for this and what needs to be done to overcome this. Please help.
Below is the code
Public Sub amount_final()
Dim Row1Crnt As Long
Dim Row2Crnt As Long
With Sheets("sheet4")
Row1Last = .Cells(Rows.Count, "B").End(xlUp).Row
End With
Row1Crnt = 2
With Sheets("sheet3")
Row2Last = .Cells(Rows.Count, "B").End(xlUp).Row
End With
There is nothing wrong with the code per se. You will get Subscript out of range error if Excel is not able to find a particular sheet which is quite obvious since you renamed it. For example, if you rename your sheet "Sheet3" to "SheetXYZ" then Excel will not be able to find it.
The only way to avoid these kind of errors is to use CODENAME of the sheets. See Snapshot
Here we have a sheet which has a name "Sample Name before Renaming"
So consider this code
Sheets("Sample Name before Renaming").Range("A1").Value = "Blah Blah"
The same code can be written as
Sheet2.Range("A1").Value = "Blah Blah"
Now no matter how many times you rename the sheet, the above code will always work :)
HTH
Sid
The basic issue is that you are referring to sheets using their common names and not their codenames. Whenever you refer to Sheets("sheet4"), you are relying on the sheet having that name in Excel. Codenames are the names assigned in Visual Basic so the end user does not interact with them/as a developer you can change the Excel names any time you like
Using code names is covered at around 9:40 in this Excel help video. You'll note they are quicker to type than the Excel names as do not require the 'Sheets()' qualifier
I couldn't see Sheets("Sheet1") in your code sample but you can switch to codenames for all sheets very quickly by finding/replacing all examples of e.g. 'Sheets("Sheet2").' with 'Sheet2.'
Refer to each sheet by their code names instead. They are set to Sheet1, Sheet2 etc as default, but you can rename them in the Properties window for each sheet if you want. This way you can write your code like below instead, regardless of what you name the sheets.
With Sheet1
Row1Last = .Cells(Rows.Count, "B").End(xlUp).Row
End With
Row1Crnt = 2
With Sheet2
Row2Last = .Cells(Rows.Count, "B").End(xlUp).Row
End With
etc...
I wanted to share my experience battling this problem. Here is the mistake I committed:
Dim DailyWSNameNew As String
lastrow = Sheets("DailyWSNameNew").Range("A65536").End(xlUp).Row + 1 -- This is wrong as I included a placeholder worksheet name in quotes
Correction:
lastrow = Sheets(DailyWSNameNew).Range("A65536").End(xlUp).Row + 1
This solved it.
I encountered this error earlier today but could not use any solution above, I did however eventually managed to solve it myself.
My situation was that I had a list contained in column A. For each cell with a value I stored the value in a variable, created a new sheet and named the sheet according to the value stored in the variable.
A bit later in the code I tried to select the newly created sheet by using the code:
Sheets(ValueVariable).Select
I encountered the "Subscript out of range" error and I couldn't figure out why. I've used similar code before with success.
I did however solve it by casting the variable as a string. Declaring the variable as a string did not seem to work for me.
So, if anyone else encounter this error and want something to try, perhaps this will work for you:
Sheets(Cstr(ValueVariable)).Select