I have a worksheet that upon opening it makes sure that every sheet has a button. So when a new sheet is present that doesn't have a button, it is set to add it. A few months ago I'm pretty sure this worked, but now (after not using this sheet for several months) I'm getting error '1004': "Unable to get the Add property of the OLEObjects class." The error occurs on the "set btn" line. What is causing this and how can I fix it?
Private btn As OLEObject
Public Const sButtonName1 As String = "btnTorqueCurveFit"
Public Const sBtnMessage1 As String = "Calculate Constant Torque Constants"
Public Const sButtonName2 As String = "btnESPCurveFit"
Public Const sBtnMessage2 As String = "Calculate Constant ESP Constants"
Public Const sButtonLeft1 As Long = 302.25
Public Const sButtonLeft2 As Long = 364.25
Private Sub AddTorqueButton(n As Worksheet)
'Add a Button to the Sheet
Set btn = n.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False, Left:=" & sButtonLeft1 &", Top:=3.75, Width:=60, Height:=57.75)
btn.Name = sButtonName1
btn.Object.Caption = sBtnMessage1
btn.Object.Font.Bold = True
btn.Object.WordWrap = True
'Modify the sheet's code to have newly added button call the general code in the module
Dim codeblock As CodeModule
Dim vbComp As VBComponent
Dim lineC As Integer
Dim Ap As String, _
Lf As String, _
Tabs As String, _
inputStr As String
Set vbComp = ActiveWorkbook.VBProject.VBComponents(n.CodeName)
Set codeblock = vbComp.CodeModule
Tabs = Chr(9)
Lf = Chr(10)
Ap = Chr(34)
inputStr = "Private Sub " & sButtonName1 & "_Click()" & Lf & Tabs & _
"ConstTorqueButtonAction ActiveSheet" & Lf & _
"End Sub"
With codeblock
lineC = .CountOfLines + 1
.InsertLines lineC, inputStr
End With
End Sub
Macro settings = 'Enable All,' Active X settings = 'Enable All,' the document is networked, but network documents are set to be trusted. It seem to be an issue with this workbook specifically as I have another workbook that use the same "set btn" style of code and it work on this machine, but the code displayed above produces an error. Any help or insight is appreciated.
The reason for the error is the way that the Left
argument is specified when calling OLEObjects.Add
. There is no need to be passing it as a string and the &
characters around it are unnecessary. In fact, that whole thing causes the error.
Since the constant sButtonLeft1
is already of type Long
, you should just be passing it directly. Therefore, instead of passing a string like this:
... , Left:=" & sButtonLeft1 &", ...
you should be calling it with the long parameter directly like this:
... , Left:=sButtonLeft1, ...
This should resolve the problem.