Runtime error 424 Compile error, Object Required - VBA Excel - vba

I need a simple bit of VBA code to work, however I keep getting runtime error 424.
I have looked over many other posts but found nothing that could help me
All I want to do is Vlookup with the id "individual" and find it in the ApplySublimits Worksheet.
Sub CommandButton1_Click()
Dim individual As String
Dim individualCap As Single
Dim subRange As Range
Set subRange = ApplySublimits.Range("B:D")
individual = "D02065"
Range("C10").Value = individual
individualCap = Application.WorksheetFunction.VLookup(individual, subRange, 2, False)
End Sub
I keep getting this error but i dont understand why. Im very new to excel and would appreciate some help or guidance.

How can a single (a floating point number) hold something starting with D. It's not 0-9. If it's hex the &hD02065 is the way to do it. Plus numbers aren't enclosed in quotes.

Declare and set applysublimits as the worksheet
Change individualCap to String
e.g.
Sub CommandButton1_Click()
Dim individual As String
Dim individualCap As String
Dim subRange As Range
Dim applysublimits As Worksheet
Set applysublimits = Sheets("Sheet1")
Set subRange = applysublimits.Range("B:D")
individual = "D02065"
Range("C10").Value = individual
individualCap = Application.WorksheetFunction.VLookup(individual, subRange, 2, False)
End Sub

Related

Set range via Range object -> Range object fails?

Can someone help me debug this piece of code?
....
Dim searchRng as Range
With Sheets("Database")
Set searchRng = Range("pointer.address:.cells(pointer.End(xlDown).Row,pointer.Column).address")
End with
I keep getting error 1004: Method 'Range' of object '_Global' failed
"pointer" is a previously defined range of one cell (B6).
After various debugging attempts, the problem seems to be connected to .address... Thats as far as I've been able to trace it back.
Thanks in advance!
Leo
The issue here is that the quotation marks are for when you are passing the name of a range to the .Range() object, but you are wanting to pass it the results of calling the .address method. If you put those method calls in quotation marks VBA wont run them and will instead try to interpret what you have in them as the name of the range you are referring to. You need to construct the range name string using these methods and pass the result to the .Range() object.
There are several ways you could do this. This first one separates out the construction of the range name and assigns that to a variable which can then be passed to .Range().
Sub test()
Dim searchRng As Range
Dim CllNameA As String
Dim CllNameB As String
Dim CllRange As String
With Sheets("Database")
CllNameA = .Range("pointer").Address
CllNameB = .Range("pointer").End(xlDown).Address
CllRange = CllNameA & ":" & CllNameB
Set searchRng = .Range(CllRange)
End With
End Sub
This next subroutine condenses the same methodology into one line. It's still doing the same thing, but as its doing it all at once its slightly more difficult for a human reader to follow.
Sub test2()
Dim searchRng As Range
With Sheets("Database")
Set searchRng = .Range(.Range("pointer").Address & ":" & .Range("pointer").End(xlDown).Address)
End With
End Sub
There are other ways of achieving the same goal, but I hope this at least sets you on the right path.

Object Required Error VBA Function

I've started to use Macros this weekend (I tend to pick up quickly in regards to computers). So far I've been able to get by with searching for answers when I have questions, but my understanding is so limited I'm to a point where I'm no longer understanding the answers. I am writing a function using VBA for Excel. I'd like the function to result in a range, that can then be used as a variable for another function later. This is the code that I have:
Function StartingCell() As Range
Dim cNum As Integer
Dim R As Integer
Dim C As Variant
C = InputBox("Starting Column:")
R = InputBox("Starting Row:")
cNum = Range(C & 1).Column
Cells(R, cNum).Select
The code up to here works. It selects the cell and all is well in the world.
Set StartingCell = Range(Cell.Address)
End Function
I suppose I have no idea how to save this location as the StartingCell(). I used the same code as I had seen in another very similar situation with the "= Range(Cell.Address)." But that's not working here. Any ideas? Do I need to give more information for help? Thanks for your input!
Edit: I forgot to add that I'm using the InputBox to select the starting cell because I will be reusing this code with multiple data sets and will need to put each data set in a different location, each time this will follow the same population pattern.
Thank you A.S.H & Shai Rado
I've updated the code to:
Function selectQuadrant() As Range
Dim myRange As Range
Set myRange = Application.InputBox(Prompt:="Enter a range: ", Type:=8)
Set selectQuadrant = myRange
End Function
This is working well. (It appears that text is supposed to show "Enter a range:" but it only showed "Input" for the InputBox. Possibly this could be because I'm on a Mac?
Anyhow. I was able to call the function and set it to a new variable in my other code. But I'm doing something similar to set a long (for a color) so I can select cells of a certain color within a range but I'm getting all kinds of Object errors here as well. I really don't understand it. (And I think I'm dealing with more issues because, being on a mac, I don't have the typical window to edit my macros. Just me, basically a text box and the internet.
So. Here also is the Function for the Color and the Sub that is using the functions. (I've edited both so much I'm not sure where I started or where the error is.)
I'm using the functions and setting the variables to equal the function results.
Sub SelectQuadrantAndPlanets()
Dim quadrant As Range
Dim planetColor As Long
Set quadrant = selectQuadrant()
Set planetColor = selectPlanetColor() '<This is the row that highlights as an error
Call selectAllPlanets(quadrant, planetColor)
End Sub
This is the function I'm using to select the color that I want to highlight within my range
I would alternately be ok with using the interior color from a range that I select, but I didn't know how to set the interior color as the variable so instead I went with the 1, 2 or 3 in the input box.
Function selectPlanetColor() As Long
Dim Color As Integer
Color = InputBox("What Color" _
& vbNewLine & "1 = Large Planets" _
& vbNewLine & "2 = Medium Planets" _
& vbNewLine & "3 = Small Planets")
Dim LargePlanet As Long
Dim MediumPLanet As Long
Dim smallPlanet As Long
LargePlanet = 5475797
MediumPlanet = 9620956
smallPlanet = 12893591
If Color = 1 Then
selectPlanetColor = LargePlanet
Else
If Color = 2 Then
selectPlanetColor = MediumPlanet
Else
If Color = 3 Then
selectPlanetColor = smallPlanet
End If
End If
End If
End Function
Any help would be amazing. I've been able to do the pieces individually but now drawing them all together into one sub that calls on them is not working out well for me. Thank you VBA community :)
It's much simpler. Just
Set StartingCell = Cells(R, C)
after getting the inputs, then End Function.
The magic of the Cells method is it accepts, for its second parameter, both a number or a character. That is:
Cells(3, 4) <=> Cells(3, "D")
and
Cells(1, 28) <=> Cells(3, "AB")
One more thing, you can prompt the user directly to enter a range, with just one input box, like this:
Dim myRange as Range
Set myRange = Application.InputBox(Prompt:="Enter a range: ", Type:=8)
The Type:=8 specifies the input prompted for is a Range.
Last thing, since you are in the learning process of VBA, avoid as much as possible:
using the Select and Activate stuff
using unqualified ranges. This refers to anywhere the methods Cells(..) or Range(..) appear without a dot . before them. That usually leads to some random issues, because they refer to the ActiveSheet, which means the behavior of the routine will depend on what is the active worksheet at the moment they run. Avoid this and always refer explicitly from which sheet you define the range.
Continuing your line of thought of selecting the Range bu Selecting the Column and Row using the InputBox, use the Application.InputBox and add the Type at the end to restrict the options of the user to the type you want (Type:= 1 >> String, Type:= 2 >> Number).
Function StartingCell Code
Function StartingCell() As Range
Dim cNum As Integer
Dim R As Integer
Dim C As Variant
C = Application.InputBox(prompt:="Starting Column:", Type:=2) '<-- type 2 inidcates a String
R = Application.InputBox(prompt:="Starting Row:", Type:=1) '<-- type 1 inidcates a Number
Set StartingCell = Range(Cells(R, C), Cells(R, C))
End Function
Sub TestFunc Code (to test the function)
Sub TestFunc()
Dim StartCell As Range
Dim StartCellAddress As String
Set StartCell = StartingCell '<-- set the Range address to a variable (using the function)
StartCellAddress = StartCell.Address '<-- read the Range address to a String
End Sub

Inserting Formula in Formula Bar

Anyone knows what's the problem with my code?
Sub reFormat()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Admin")
ws.Range("C21").Formula = "=""S4&""AA5&""AA6&""AA7&""AA8&""AA9&""AA10" 'returns applica-
tion defined or object-defined error
End Sub
And I want the output of this code to be: =S4&(AA5&AA6&AA7&AA8&AA9&AA10)
Thanks for the help!
Your formula is fundamentally invalid. The string evaluates to this:
="S4&"AA5&"AA6&"AA7&"AA8&"AA9&"AA10
Which isn't a valid Excel formula.
You have too many quotes. If these are cell references and your formula intends to concatenate them, and you want your string to evaluate to this:
=S4&(AA5&AA6&AA7&AA8&AA9&AA10)
Then you could just do this:
.Formula = "=S4&(AA5&AA6&AA7&AA8&AA9&AA10)"

VB Com Error for Naming Sheets on a Worksheet

I keep getting an error that says
"An unhandled exception of type
'System.Runtime.InteropServices.COMException' occurred in
Microsoft.VisualBasic.dll"
Additional information: Exception from HRESULT: 0x800A03EC"
on the line where I'm trying to change the name of the sheets from Workbook reportApp. On my timeWorkbook there are headings in cells A1, then cell D1, and so on.
I want it to loop until there is no more values, but I can't change the name. I can change the name of the sheets in that workbook if I put reportApp.Sheets(s).Name = "Name this sheet", but I don't want to do that. I was wondering if there was any problem with my type or code that would get around this?
Private Sub generateReportButton_Click(sender As Object, e As EventArgs) Handles generateReportButton.Click
Dim timeApp As Excel.Application = New Excel.Application
Dim timeClockPath As String = "C:\Users\njryn_000\Desktop\Project ACC\Clock-In Excel\TimeClock.xlsx"
Dim timeWorkbook As Excel.Workbook = timeApp.Workbooks.Open(timeClockPath, ReadOnly:=False, IgnoreReadOnlyRecommended:=True, Editable:=True)
Dim timeWorksheet As Excel.Worksheet = timeWorkbook.Worksheets("TA")
Dim reportApp As Excel.Application = New Excel.Application
Dim reportPath As String = "C:\Users\njryn_000\Desktop\Project ACC\Report\Blank Timecard Report9.xlsx"
Dim reportWorkbook As Excel.Workbook = reportApp.Workbooks.Open(reportPath, ReadOnly:=False, IgnoreReadOnlyRecommended:=True, Editable:=True)
Dim reportWorksheet As Excel.Worksheet = reportWorkbook.Worksheets("Sheet" & 1)
Dim s As Integer
Dim i As Integer
Dim f As Integer
Dim taName As String
Dim taID As String
i = 0
f = 0
s = 1
With timeWorksheet.Range("A1")
Do
i += 3
s += 1
reportApp.Sheets(s).Name = timeWorksheet.Range("A1").Offset(0, i).Value
Loop Until IsNothing(timeWorksheet.Range("A1").Offset(0, 0).Offset(0, i).Value)
You've already solved your problem but you may not be able to add an answer yet so here is some feedback.
When you use a With block you can then refer to whatever you referenced at the top of that block with a single dot ('.') after that. Its a syntax which reduces writing the same thing over and over. In the snippet below I've removed all references to timeWorksheet.Range("A1") and added a leading dot.
With timeWorksheet.Range("A1")
Do
i += 3
s += 1
' Since you are using a With block this statement is simplified.
reportApp.Sheets(s).Name = .Offset(0, i).Value
' I removed the .Offset(0, 0) as it is redundant.
' If you have it in to solve a bug you can put it back.
Loop Until IsNothing(.Offset(0, i).Value)
' More code here...
End With
Also you've realised that you can use the Val() function to fix your code. Reading the documentation, it explains that this function will take a string and begin reading a number from it, ignoring whitespace. As soon as it reaches a non-numeric, non-whitespace character it stops and returns the number ignoring whatever else is in the string.
It seems that this isn't really solving your problem, it just works around it. I'd look at what other characters are present in the cells you are looping through and deal with them explicitly. Otherwise you might end up with strange results.

Visio VBA: Invalid Parameter in Nested Loop

In Microsoft Visio Professional 2010 I've isolated the error I've been getting to this little code snippet. On the page is a container holding 2 shapes and I want to iterate through those shapes within another loop. But I keep getting an invalid parameter error.
My attempt at a solution is the top block, but it only works with the same definition for the inner loop. It seems like something is changing during the 2nd iteration of the outer loop, but I'm not sure. I feel it has to do with the way a For Each loop is defined.
Sub Nested_Loop_Error()
Dim a As Variant
Dim b As Variant
Dim lngs() As Long
'This Works
lngs = ActiveDocument.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
For a = 0 To 1
For Each b In lngs
'Do nothing
Next b
Next a
'This does not work
For a = 0 To 1
For Each b In ActiveDocument.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
MsgBox "In Loop for a=" & a
Next b
Next a
End Sub
Edit:
I've been playing around with it and got it to work, but what I'm really interested in is why it works. The 2nd block of code fails when a=1, giving an invalid parameter in the line docMyDoc.Pages...
The following is the code showing the difference of using a variant or a document variable to define the ActiveDocument within the loop. Using the debugger I can't see a difference in how docMyDoc or varMyDoc are defined.
Sub Nested_Loop_Error2()
Dim a As Variant
Dim b As Variant
Dim docMyDoc As Visio.Document
Dim varMyDoc As Variant
'This works
For a = 0 To 1
Set varMyDoc = ActiveDocument
For Each b In varMyDoc.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
MsgBox "Using variant, a=" & a
Next b
Next a
'This does not work
For a = 0 To 1
Set docMyDoc = ActiveDocument
For Each b In docMyDoc.Pages(1).Shapes.ItemFromID(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
MsgBox "Using document, a=" & a
Next b
Next a
End Sub
Using the Variant type doesn't help the compiler much: The variable called "b" should be of type Long, and the "a" variable of type Integer.
This said, you're not using the "a" variable but to repeat twice what you do in the inner loop (Msgbox), but nothing else changes.
Moreover, you need to reference the shape whose ID is b, that you're not doing.
And another tip: don't name variables after their type, but after their semantics.
I think that what you intended to do is something like the example in GetMemberShapes method's reference in MSDN:
Sub Nested_Loop()
Dim lngMemberID as Long
Dim vsoShape as Visio.Shape
Dim j as Integer
For j = 0 to 1
For Each lngMemberID In ActiveDocument.Pages(1).Shapes(1).ContainerProperties.GetMemberShapes(visContainerFlagsDefault)
Set vsoShape = ActivePage.Shapes.ItemFromID(memberID)
Debug.Print vsoShape.ID
Next lngMemberID
Next j
End Sub
Here, your vsoShape variable will refer first to one, then to the other of your shapes. And it will work even if you have more shapes in your page.
That's the good thing of Collections and the For Each loop: Collections are special objects made up as a list of other objects. They have their own methods, as Item, or Count, and shortcuts, like using a number between parenthesis to retrieve an individual object from the collection (as in Pages(1)).
What you do with For Each is to iterate through all the objects in the collection (or all the values in an array).
For your purposes, I'd try the following general structure:
dim oPage as Visio.Page
dim oShape as Visio.Shape
dim oInnerShape as Visio.Shape
For each oPage In ActiveDocument.Pages
For each oShape in oPage.Shapes
If oShape.Master.Name = "xxx" Then ' You can check the type of the shape
For each oInnerShape In oShape
' set and compute width and height
Next oInnerShape
' set and compute width and height of the containing shape
End If
Next oShape
' Rearrange shapes
Next oPage
You can construct an array storing the shape IDs, width and height, while iterating through the shapes, then use that array to rearrange the shapes.
Regards,
I don't have Visio on my computer but are you certain that the first nested loop worked?
I have doubt in lngs = ActiveDocument.Pages(1)... with Dim lngs() As Long:
Excel VBA will throw "Type mismatch" error with trying to store arr = Array(1,2) with Dim arr() As Long. Better off Dim lngs As Variant even if you know it's an array of Long being returned.
The second nested loop works in theory.