Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Here is my code in creating a command button in sheet1 and adding code in module:

VB
Dim xlMod As Microsoft.Vbe.Interop.VBComponent

Dim objBtn As Object
       Dim celLeft As Integer
       Dim celTop As Integer
       Dim celWidth As Integer
       Dim celHeight As Integer


       celLeft = xlWorkSheet1.Range("d5").Left
       celTop = xlWorkSheet1.Range("d5").Top
       celWidth = xlWorkSheet1.Range("d5").Width
       celHeight = xlWorkSheet1.Range("d5").Height



       objBtn = xlWorkSheet1.OLEObjects.Add(ClassType:="Forms.Commandbutton.1", link:=False, _
           displayasicon:=False, Left:=celLeft, Top:=celTop, Width:=celWidth, Height:=celHeight)

       xlWorkSheet1.commandbutton1.caption = "Generate Sheet 2"
              xlWorkSheet1.commandbutton1.Height = 33
               xlWorkSheet1.commandbutton1.Width = 125
       xlWorkSheet1.commandbutton1.font.size = "12"

xlMod = xlWorkBook.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule)
      
       Dim codeString As New StringBuilder
       codeString.AppendLine("Public Sub SaySomething()")
       codeString.AppendLine("MsgBox ""Hello""")
       codeString.AppendLine("End Sub")
      
       xlMod.CodeModule.AddFromString(codeString.ToString)


All I want is to put a vba code inside the sheet1 commandbutton1_click event and not in other Module.

Please help me.

What I have tried:

VB
xlMod = xlWorkBook.VBProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule)
      
       Dim codeString As New StringBuilder
       codeString.AppendLine("Public Sub SaySomething()")
       codeString.AppendLine("MsgBox ""Hello""")
       codeString.AppendLine("End Sub")
      
       xlMod.CodeModule.AddFromString(codeString.ToString)
Posted
Updated 13-Apr-19 5:55am

1 solution

Quote:
How to put a VBA code inside command button of excel sheet using VB.NET?

"<vba code="" inside="" command="" button"="" does="" not="" exist.="" a="" button="" can="" only="" call="" subroutine="" by="" its="" name.
<pre="" lang="vb">
xlWorkSheet1.commandbutton1.caption = "Generate Sheet 2"
xlWorkSheet1.commandbutton1.Height = 33
xlWorkSheet1.commandbutton1.Width = 125
xlWorkSheet1.commandbutton1.font.size = "12"

You are already setting some properties of commandbutton1, linking some code to a button event is just setting another property, why is it so difficult?
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900