simple vba code gives me run time error 91 object variable or with block not set - vba

So I have a simple little macro/sub defined when a command button is clicked. The problem is it gives me:
Run Time Error '91' : Object Variable or With Block not Set
My code is:
Dim rng As Range
rng = Sheet8.Range("A12") '<< ERROR here
rng.Value2 = "1"
I just want to set Cell "A12" in Sheet8.
Thanks!

You need Set with objects:
Set rng = Sheet8.Range("A12")
Sheet8 is fine.
Sheet1.[a1]

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version.
Or the other way, the object is not getting created and thus the Value2 property is not available for the object.

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1
below test code for ref.
Sub test()
Dim rng As Range
Set rng = Range("A1")
rng.Value2 = 1
End Sub

Related

How do I find out why I get an error when writing to an Excel cell with VBA?

I'm still fairly new to VBA and struggling with its limitations (and mine!). Here's my code:
Sub updateCache(CacheKey As String, CacheValue As Variant)
Dim DataCacheWorksheet As Worksheet, CacheRange As Range, Found As Variant, RowNum As Integer
Set DataCacheWorksheet = ThisWorkbook.Worksheets("DataCache")
Set CacheRange = DataCacheWorksheet.Range("A1:B999")
Set Found = CacheRange.Find(What:=CacheKey)
If Found Is Nothing Then
RowNum = CacheRange.Cells(Rows.Count, 2).End(xlUp).Row
DataCache.Add CacheKey, CacheValue
On Error Resume Next
DataCacheWorksheet.Cells(1, 1).Value = CacheKey
DataCacheWorksheet.Cells(1, 2).Value = CacheValue
Else
'Do other things
End If
End Sub
When I step through the code, Excel simply exits the sub at the line DataCacheWorksheet.Cells(1, 1).Value = CacheKey, with no error. So, two questions:
What's the bug that's preventing the value from being updated?
Why does Excel ignore my On Error command?
Edit: If I run the line in the IDE's "Immediate" box, I get the error "Run-time error '1004' Application-defined or object-defined error. I get the same error regardless of the value of CacheKey (I tried Empty, 1234 and "Hello").
Edit 2: If I modify the sub so that CacheKey and CacheValue are hardcoded and the reference to DataCache is removed, and then I run the sub standalone it works. So why doesn't it work when called from another function? Is it possible that Excel is locking cells while doing calculations?
Not sure if this applies, but you mentioned you were calling this macro from another function. If you are calling it from a function, depending on how you are calling it, that would explain your problem. For example, a worksheet function entered into a cell cannot modify another cell on the worksheet. And the attempt to do so will result in the macro merely exiting at that point, without throwing a VBA error.
How to work around this depends on specifics you have yet to share. Sometimes, worksheet event code can be useful.
Ok, wasn't about to write an answer, but there are 3 things you should modify in your code:
Found As Range and not As Variant
RowNum As Long in case it's a row after ~32K
To trap errors usually On Error Resume Next won't help you, it will just jump one line of code. You need to handle the error situation.
Modified Code
Sub updateCache(CacheKey As String, CacheValue As Variant)
Dim DataCacheWorksheet As Worksheet, CacheRange As Range, Found As Range, RowNum As Long ' < use Long instead of Integer
Set DataCacheWorksheet = ThisWorkbook.Worksheets("DataCache")
Set CacheRange = DataCacheWorksheet.Range("A1:B999")
Set Found = CacheRange.Find(What:=CacheKey)
If Found Is Nothing Then ' check if not found in cache (*Edit 1)
RowNum = CacheRange.Cells(Rows.Count, 2).End(xlUp).Row
DataCache.Add CacheKey, CacheValue ' I assume you have a `Dictionary somewhere
' On Error Resume Next <-- Remove this, not recommended to use
DataCacheWorksheet.Cells(1, 1).Value = CacheKey
DataCacheWorksheet.Cells(1, 2).Value = CacheValue
Else
'Do other things
End If
End Sub

How to iterate over a range of cells in Excel/VBA?

Dim works As Worksheet
Set works = ThisWorkbook.Sheets("Sheet1")
Dim txt As Variant
myrange = works.Range("C1:C9")
For Each txt In myrange
If InStr(1, txt, "£", vbTextCompare) > 0 Then
Debug.Print txt.Value '<..Object required err
Debug.Print works.Range("C" & txt).Value '<..Object required err
Debug.Print works.Cells(txt, 1).Value '<..Object required err
Debug.Print txt.Offset(0, 1).Value '<..Object required err
End If
Next txt
I'm trying to get the value of the cell that contains the "£" and then delete it . I'm getting `the object defined error in any case. I've tried 3 different options and still getting the error. I'm new to VBA and still learning. How can I fix this, and why am I getting the error?
One problem is the line myrange = works.Range("C1:C9"). It should have Set before it, like:
Set myrange = works.Range("C1:C9")
This way you ensure you are making a reference assignment, instead of a value assignment. Without it, you're telling VBA that you want the value of the cells to go in your variable. With it, you're telling VBA that you want your variable to point to that range.
Since you did not explicitly declare myrange as a Range object, VBA implicitly declared it Variant and treated it as a String. So, in the loop, txt was a String too, not a Range as you expected. Hence your error.
If you had Dim myrange As Range in the beginning, your assignment without Set would have failed and you'd have fixed it immediately.
But there's a simple habit that prevents this kind of error: in the top of your module, insert Option Explicit. This way, you have to explicitly declare ALL your variables, which means VBA won't assume they're Variant.
You can even make that automatic by checking the relevant option in Tools > Options.

Excel vba variable not defined when using range variable

I have function testFunc that takes Range as an argument, loops thorugh its cells and edits them. I have sub testSub that tests two cases: first is when I pass the current workbook's range to testFunc through: 1. variable Range 2. just as an argument testFunct(...Range("A1:A16")).
The second case is when I open another workbook and do the same - pass one of its worksheets range to the testFunc directly or via variable.
Function testFunc(aCol As Range)
Dim i As Integer
i = 0
For Each cell In aCol
MsgBox (cell.Value)
cell.Value = i
i = i + 1
Next
testFunc = i
End Function
Sub testSub()
Dim origWorkbook As Workbook
Set origWorkbook = ActiveWorkbook
Dim aRange As Range
Set aRange = ThisWorkbook.Sheets("sheet 1").Range("A1:A16")
Dim dataWorkbook As Workbook
Set dataWorkbook = Application.Workbooks.Open("Y:\vba\test_reserves\test_data\0503317-3_FO_001-2582480.XLS")
Dim incomesNamesRange As Range
Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(dataWorkbook.Sheets("1").Range("A1:A20"))
origWorkbook.Worksheets("Ëèñò2").Cells(1, 50) = testFunc(incomesNamesRange)
' testFunc aRange
'origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(aRange) '<---good
' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(ThisWorkbook.Sheets("sheet 1").Range("A1:A16"))
End Sub
The problem is, as I indicated with comments, when I open a foreign workbook and pass its range through a variable it gives an error variable not definedFor Each cell In aCol`, while all other cases (including passing range variable of the current workbook) work fine.
I need testFunc to stay a Function, because it's a simplfied example of some code from bigger program which needs to take a returned value from a function. And I need to store that Range in a variable too, to minimize time of the execution.
EDIT: As pointed out in the comments, I replaced Cells(1,5) with origWorkbook.Worksheet("shee t1").Cells(1,5) and fixed variable name, but the original mistake changed to variable not defined. I edited the title and body of the question.
The default name for the worksheet shouldn't have a space in it.
Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
Change this to:
Set incomesNamesRange = dataWorkbook.Worksheets("Sheet1").Range("A1:A20")
And see if that fixes it.

Excel VBA - Dynamic Range obj referencing

Im doing what seems like a simple dynamic range. However, Im getting the following error:
"Error: Set method of range class failed"
VBA doesnt like the dropdownRange obj & throws the above error on the second last line of code below. I am using this range to be used in validation dropdown list further down the list.
Dim mainTab As Object 'Tab 'main'
Dim tranTypeSize As Integer 'Length of entries for transaction type
Dim dropdownRange As Range 'Dynamic range for dropdown
Set mainTab = Sheets("Main")
With Sheets("Misc")
tranTypeSize = .Cells(Rows.Count, 1).End(xlUp).Row
Set dropdownRange = .Range("A1:A" & tranTypeSize)
dropdownRange.Select
End With
I assume that you mean Select method of range class failed. If so, the problem is that Sheet("Misc") isn't active.
To fix it, put .Select as the first line of the With block.

Using range-variable in multiple worksheets

I have an issue while using a variable containing a range.
I've declared the variable "rng" globally in the workbook module:
Public rng As Range
Now in a worksheet module I set the variable after clicking on a checkbox and define a range for it:
Sub CheckBox1_Click()
Set rng = Range("D8:Q51")
If Me.OLEObjects("checkbox1").Object.Value Then
Call clear(rng)
Else
Call aus(rng)
End If
End Sub
I always get an error when calling the sub "aus(rng)" which says:
error 438, object doesn't support this property or method
"aus(rng)" contains the following code:
Worksheets(5).rng.Copy Worksheets("aktuell").rng
Btw: using the range-variable in the same worksheet the module is connected to doesn't throw out an error. So the error somehow has to correlate with "Worksheets(5)".
When you define a Range with Set and you don't define the parent objects of Workbook or Worksheet, it will default to ActiveWorkBook and ActiveWorkSheet. Therefore it is like writing:
Set rng = ActiveWorkbook.ActiveSheet.Range("D8:Q51")
When you use the rng later in the code, you try and assign it under a Sheet which is basically writing:
Worksheets(5).ActiveWorkbook.ActiveSheet.Range("D8:Q51").Copy
Which we know is incorrect syntax and will error.
As a workaround, you could use the following code:
Worksheets(5).Range(rng.Address).Copy Worksheets("aktuell").Range(rng.Address)