adding code to command button in word from excel VBA

Hi-

I am creating a document in word with excel VBA.  I figured out how to
add a command button to word from excel VBA, but I can not figure out
how to add code to that command button for when the command button is
clicked on.  I do not want to use a userform.  I know how to add code
to the button i create in an excel document, but I can't seem to add
code to a button in word, using excel VBA.  Here is the code I have
created so far.  I wrote messages in the code to tell you what i was
doing and which part i am having problems with.  I have been working on
this for several days and would appreciate any help you can give me.
THank you!


Dim Wdoc As Word.document
Dim Wapp As Word.Application
Dim rng As Word.Range
Dim shp As Word.InlineShape

'this created a word document
Set Wapp = CreateObject("Word.Application")
    Wapp.Visible = True
    Wapp.Documents.Add
    Set Wdoc = Wapp.ActiveDocument

Set rng = Wdoc.Paragraphs.Last.Range

'this created my command button and named it
        Set shp =
rng.document.InlineShapes.AddOLEControl(ClassType:="Forms.Commandbutton.1",
_
               Range:=Wdoc.Paragraphs.Last.Range)

        shp.OLEFormat.Object.Caption = "Add Orbit"
        shp.OLEFormat.Object.Name = "OrbitButton"

'this is the part that doesn't work.  I am trying to add code for when
it is clicked on.  This is one of
'the methods i tried.
        With
rng.document.VBProject.VBComponents(ActiveDocument.CodeName).CodeModule
            .InsertLines .CreateEventProc("Click",
shp.OLEFormat.Object.Name) + 1, _
                "Msgbox ""You Clicked The Button"" "
        End With


'i also tried changing the previous code to this and it still did not
work.

        With
thisWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule
            .InsertLines .CreateEventProc("Click",
shp.OLEFormat.Object.Name) + 1, _
                "Msgbox ""You Clicked The Button"" "
        End With

0
1/3/2007 6:03:57 PM
excel 39879 articles. 2 followers. Follow

2 Replies
716 Views

Similar Articles

[PageSpeed] 26

Can be a button on toolbar?
Try the code below (or something like this). This code I use in Excel to 
create a button on tool bar. Maybe if you add your "Wdoc" before 
"CommandBars."... (sorry but i don'r know how to use OLEControl)


Const strNameCommandBar As String = "Test"
Const strNameCommandBarButton As String = "Test"

Sub CreateCustomButton()

Dim myNewBar As CommandBar
Dim customButton As CommandBarButton

Dim x As CommandBar, LastBar As CommandBar
Dim LastRow As Integer

    On Error Resume Next
    CommandBars(strNameCommandBar).Delete

    'Put the button after the last button on toolbar
    For Each x In Application.CommandBars
        If x.Visible = True And x.Position = msoBarTop Then
            If x.RowIndex > LastRow Then
                Set LastBar = x
                LastRow = x.RowIndex
            End If
        End If
    Next x

    Set myNewBar = CommandBars.Add(Name:=strNameCommandBar, 
Position:=msoBarTop, Temporary:=True)
    'Set myNewBar = CommandBars.Add(Name:=strNameCommandBar, 
Position:=msoBarFloating, Temporary:=True)
    With myNewBar
        .Enabled = True
        .Left = LastBar.Left + LastBar.Width + 1
        .RowIndex = LastRow
        .Visible = True
    End With

    Set customButton = myNewBar.Controls.Add(Type:=msoControlButton, ID:=23)
    customButton.Caption = strNameCommandBarButton
    customButton.FaceId = 92
    customButton.TooltipText = "Corrige Links de fun��es de migra��o"
    customButton.Style = msoButtonIconAndWrapCaption 'msoButtonCaption
    customButton.OnAction = "MyMacro"

    On Error GoTo 0
End Sub

Sub DeleteCustomButton()
    On Error Resume Next 'In case it has already gone.
    Application.CommandBars(strNameCommandBar).Controls(strNameCommandBarButton).Delete
    Application.CommandBars(strNameCommandBar).Delete
    On Error GoTo 0
End Sub

Sub MyMacro()
MsgBox "My Macro"
End Sub


-- 

Rodrigo Ferreira
Brazil


"hornbecky83" <hornbecky83@gmail.com> escreveu na mensagem 
news:1167847437.397330.191430@42g2000cwt.googlegroups.com...
> Hi-
>
> I am creating a document in word with excel VBA.  I figured out how to
> add a command button to word from excel VBA, but I can not figure out
> how to add code to that command button for when the command button is
> clicked on.  I do not want to use a userform.  I know how to add code
> to the button i create in an excel document, but I can't seem to add
> code to a button in word, using excel VBA.  Here is the code I have
> created so far.  I wrote messages in the code to tell you what i was
> doing and which part i am having problems with.  I have been working on
> this for several days and would appreciate any help you can give me.
> THank you!
>
>
> Dim Wdoc As Word.document
> Dim Wapp As Word.Application
> Dim rng As Word.Range
> Dim shp As Word.InlineShape
>
> 'this created a word document
> Set Wapp = CreateObject("Word.Application")
>    Wapp.Visible = True
>    Wapp.Documents.Add
>    Set Wdoc = Wapp.ActiveDocument
>
> Set rng = Wdoc.Paragraphs.Last.Range
>
> 'this created my command button and named it
>        Set shp =
> rng.document.InlineShapes.AddOLEControl(ClassType:="Forms.Commandbutton.1",
> _
>               Range:=Wdoc.Paragraphs.Last.Range)
>
>        shp.OLEFormat.Object.Caption = "Add Orbit"
>        shp.OLEFormat.Object.Name = "OrbitButton"
>
> 'this is the part that doesn't work.  I am trying to add code for when
> it is clicked on.  This is one of
> 'the methods i tried.
>        With
> rng.document.VBProject.VBComponents(ActiveDocument.CodeName).CodeModule
>            .InsertLines .CreateEventProc("Click",
> shp.OLEFormat.Object.Name) + 1, _
>                "Msgbox ""You Clicked The Button"" "
>        End With
>
>
> 'i also tried changing the previous code to this and it still did not
> work.
>
>        With
> thisWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule
>            .InsertLines .CreateEventProc("Click",
> shp.OLEFormat.Object.Name) + 1, _
>                "Msgbox ""You Clicked The Button"" "
>        End With
> 


0
cabelo (15)
1/3/2007 7:32:01 PM
Thank you all for your help.  I did have to change my security setting.
 I also had to add a few more things, such as activating the word
application.  However, now i am having a problem with adding more than
one button to the document and the naming I give it.  I created a for
loop, so when j is equal to a number greater than 1, vba will run
through my code several times.  But after the first time I run through
my code the object.name = "orbitbutton" doesn't work.  I get ambiguos
name and automation error.  I tried adding a j to the object name, so
the code is object.name = "orbitbutton" & j and everytime i run through
the code, it will name the button: orbitbutton1, orbitbutton2...
However, this still won't run after the first run.  I get the same
error, ambiguos name and automation error.  Below is the code I have
come up with. Hope you can help me!  Sarah

Dim Wdoc As Word.document
Dim Wapp As Word.Application
Dim rng As Word.Range
Dim shp As Word.InlineShape
Dim scode as String

'this created a word document
Set Wapp = CreateObject("Word.Application")
     Wapp.Visible = True
    Wapp.Documents.Add
    Set Wdoc = Wapp.ActiveDocument

 Set rng = Wdoc.Paragraphs.Last.Range

'this started my loop
For j = 1 To y

'this created my command button and named it

Set shp =
rng.document.InlineShapes.AddOLEControl(ClassType:="Forms.Commandbutton.1",
_
        Range:=Wdoc.Paragraphs.Last.Range)

        shp.OLEFormat.Object.Caption = "Add Orbit"
        shp.OLEFormat.Object.Name = "OrbitButton" & j


        scode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()"
& vbCrLf & _
                 " MsgBox ""You Clicked the CommandButton""" & vbCrLf &
_
                 "End Sub"

         Application.ActivateMicrosoftApp xlMicrosoftWord


Wdoc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString
scode
  Next j

Alok wrote:
> The first version of your code works fine.
>
> You did not say what error you were getting but the only error I got while
> using your code was one related to increased level of security in Excel 2003
> and Word 2003. I went into Word, Tools/Macro/Security/Trusted Sources and
> selected 'Trust Access to Visual Basic Project'. Once I did this the code
> created the button as desired and invoked the code.
>
> Alok
>
> "hornbecky83" wrote:
>
> > Hi-
> >
> > I am creating a document in word with excel VBA.  I figured out how to
> > add a command button to word from excel VBA, but I can not figure out
> > how to add code to that command button for when the command button is
> > clicked on.  I do not want to use a userform.  I know how to add code
> > to the button i create in an excel document, but I can't seem to add
> > code to a button in word, using excel VBA.  Here is the code I have
> > created so far.  I wrote messages in the code to tell you what i was
> > doing and which part i am having problems with.  I have been working on
> > this for several days and would appreciate any help you can give me.
> > THank you!
> >
> >
> > Dim Wdoc As Word.document
> > Dim Wapp As Word.Application
> > Dim rng As Word.Range
> > Dim shp As Word.InlineShape
> >
> > 'this created a word document
> > Set Wapp = CreateObject("Word.Application")
> >     Wapp.Visible = True
> >     Wapp.Documents.Add
> >     Set Wdoc = Wapp.ActiveDocument
> >
> > Set rng = Wdoc.Paragraphs.Last.Range
> >
> > 'this created my command button and named it
> >         Set shp =
> > rng.document.InlineShapes.AddOLEControl(ClassType:="Forms.Commandbutton.1",
> > _
> >                Range:=Wdoc.Paragraphs.Last.Range)
> >
> >         shp.OLEFormat.Object.Caption = "Add Orbit"
> >         shp.OLEFormat.Object.Name = "OrbitButton"
> >
> > 'this is the part that doesn't work.  I am trying to add code for when
> > it is clicked on.  This is one of
> > 'the methods i tried.
> >         With
> > rng.document.VBProject.VBComponents(ActiveDocument.CodeName).CodeModule
> >             .InsertLines .CreateEventProc("Click",
> > shp.OLEFormat.Object.Name) + 1, _
> >                 "Msgbox ""You Clicked The Button"" "
> >         End With
> >
> >
> > 'i also tried changing the previous code to this and it still did not
> > work.
> >
> >         With
> > thisWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule
> >             .InsertLines .CreateEventProc("Click",
> > shp.OLEFormat.Object.Name) + 1, _
> >                 "Msgbox ""You Clicked The Button"" "
> >         End With
> > 
> >

0
1/3/2007 9:45:23 PM
Reply:

Similar Artilces:

option button
Hi I need some help! I have a column with results from a survey. The results are in text but do have a ranking, e.g. the results can be A,B,C,D or E. I now want to create an option button or similar where I can let the user choose to cap the results so e.g. the maximum result is a B and then all A results should show up as B's. Is this possible? Thanks You'll need a helper column to do this. Try something like this: =IF(B3<=C$1,C$1,B3) B3 is the survey result, C1 is the "Cap" value. HTH, Barb Reinhardt "Andreas" wrote: > Hi > > I need som...

Looking for Excel Help
I'm a very novice Excel user and am looking for a little help with creating a formula for a spreadsheet I'm creating for my personal use. I would appreciate some assistance if possible. Thanks in advance. Dan --- Message posted from http://www.ExcelForum.com/ Hi Dan! Post a sample of what you want to do. Your question is just a tad open ended <g> -- Regards Norman Harker MVP (Excel) Sydney, Australia njharker@optusnet.com.au Excel and Word Function Lists (Classifications, Syntax and Arguments) available free to good homes. "DanB4105" <DanB4105.ywtpa@excelfor...

New to excel
Hi All, I'm new to Excel ( and to this forum :) ) and so I hope somebody may b able to help me. I've got 2 questions.... QUESTION 1 I've got a spreadsheet which takes data from one worksheet and uses i to calculate data in a second worksheet using the following code formula: =IF('4th November 2005'!B19="","nothing here dude",IF(B19<'4th Novembe 2005'!B19,"UP",IF(B19='4th November 2005'!B19,"Same",IF(B19>'4t November 2005'!B19,"DOWN")))) The problem is, when I create a new worksheet I have...

Excel button problem
Hi All I have a macro that copies a worksheet in the active workbook and puts it into a new workbook - then formats it and deletes any buttons on the worksheet. On the first click on the button the macro works ok. On the second click, it fails because the all assigned macros on all buttons in the active workbook changed from "mba" to "book1!mba". Book 1 doesn't exists (wasn't opened, wasn't saved, doesn't have the macros). I've never experienced this problem before?? Can anyone help to solve this problem? FYI The macro to do this is c...

AD Sync problem
Hello, One of my DC was disconnected from the network for quite a long time and cannot be synchronized with AD anymore. I have been trying to apply the http://support.microsoft.com/kb/325850/en-us procedure to reset the machine account password. After launching the command "netdom resetpwd /S: ....." I've got the following error message : "The machine account password for the local machine could not be reset. Echec d'ouverture de session : unknown user or incorrect password. The command failed to complete successfully." ANy idea to help me ? Man...

Excel 97 #9
Please can anyone help??? I have two columns in Excel 97. The first contains a list of statu values eg. pending, or granted or withdrawn. The second contains date eg.01/12/1997, 05/06/2003. I woudl like to know how to get all th granted apps before 31/12/2003. Can anyone help please -- Message posted from http://www.ExcelForum.com theres many ways, but an easiest way would be to do a sort. Highlight the 2 columns, click on data, then sort, then sort by status, then by date. this should group them all together. hope this helps...toe >-----Original Message----- >Please can anyo...

Unable to open .docx documents in Word 2002
I cannot open word documents sent with .docx extendion in word 2002. I checked my language setting and it is English. What is wrong? Download the Compatibility Pack. http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en -- JoAnn Paules MVP Microsoft [Publisher] Tech Editor for "Microsoft Publisher 2007 For Dummies" "Johnpm" <Johnpm@discussions.microsoft.com> wrote in message news:43E248E8-5D83-4E91-9743-CE12CCD6A443@microsoft.com... >I cannot open word documents sent with .docx extendi...

explanation of codes in Visual Basic when creating User form
Hi, I am trying to create a user form in Visual Basic however I'm trying to teach myself by reading/watching tutorials. (www.contectures.o.ca, etc) A lot of the instructions I am seeing simply give the code rather than explain how to actually write one from scratch. So... I need to know what each 'term' means so I can understand how the codes work. Any help is much appreciated :) One of the first codes is for the Add button Private Sub cmdAdd_Click() Dim iRow As Long Dim ws As Worksheet Set ws = Worksheets("PartsData") What d...

How do I Remove a Split from my Comments in Excel 2003? #2
I have set my current workbook to split/freeze the first column and first 2 rows. Now, when I add a comment to the second row (in any column) my comments are cut off if I should scroll down. I don't ever remember the behavior before. And I don't know what I've done to enable it but it's really annoying. How do turn this off ? ...

learning Excel #3
Hi, I was considering learning Excel as an additional tool for my data analysis work. Is it better to use data sets that I have previously used with SPSS and apply the same analysis tools as in SPSS? For applying the appropriate tools, I was considering using excel's online help. The second option I have is to use some excel book for data analysis and apply the techniques to data sets provided with the book. Any suggestions????? regards Metal ...

unable to paste Excel 2003 chart into Outlook 2003
(This was posted on "excel.charting" group.) I have a user who's unable to paste an Excel 2003 chart into Outlook 2003 email message. In Outlook options, the checkbox is selected for "Use Microsoft Office Word 2003 to edit e-mail messages". When I tested this on my own computer running the same version of Office, if the box is check, I have no problem pasting; if this box is cleared, I cannot paste. But on his computer, it doesn't work regardless. Thanks and regards, TL ...

setup Windows Mail as Word 2003 default emailer
All I can do is setup Outlook. I do not use Outlook. I would like to email Word docs using MS Windows Mail (new version of Express) In the Windows Start area, type Regedit into the search bar and then start the Registry Editor and go to HKEY_CURRENT_USER>Software>Clients>Mail Right Click on the (Default) item and then on Modify and in the Value data: field enter Windows Mail so that after you click OK, you have (Default) REG_SZ WIndows Mail -- Hope this helps. Please reply to the newsgroup unless you wish to avail yourself of my services on a pa...

Excel corrupts when asking to update vlookups
We are experiencing weird behavior with some Office 2K3 Excel spreadsheets that contain lots of calculations, but no macros. On some pc’s Excel acts normally, on others you get the error. I have a couple of screen shots available. Any help is appreciated. If desired, send your file to my address below. I will only look if: 1. You send a copy of this message on an inserted sheet 2. You give me the newsgroup and the subject line 3. You send a clear explanation of what you want 4. You send before/after examples and expected results. -- Don Gu...

Excel VBA
When you select the autofilter, the drop down list is created from the unique data in that column. Is there any way to customize this list, so the changes are permanent? For instance, I might have in one(1) column the following 4 row entries: red, blue, green (all are single cell entries) red, blue red blue, green I want my autofilter drop down list to read: red instead of red, blue, green blue red, blue green red blue, green (like normal) If I chose red from the drop down list...

Problem with named range for a large spreadsheet in Excel 2007
Hello, I am trying to generate a large Excel spreadsheet apprx. 10000 rows and 40 columns. I am generating defined name section in the Workbook.xml part of the XLSM package. Here is a sample entry from that section <definedName name="_._44802_._0_._0_._0_._top_line" localSheetId="0" hidden="1">Sheet1!$B$2</definedName> Although the generation goes fine, I can not open the spreadsheet as the Excel throws an error message saying the package is corrupt. But this is not the case if the spreadsheet is small say, 200 rows by 10 columns. ...

Uninstall of mappoint has caused errors with excel
Hi, I am running Office 2003 on the terminal server (windows 2003) and had a copy of mappoint as well. This is a mapping program. We ininstalled mappoint which has caused an error message with Excel and other office products. The error says "Cd:\documents and settings\administrator.ocrdc1\application data\microsoft\addins c:\Program files\common files\microsoft shared\geography\mpoai9.dll is not a valid add-in." I then click OK and excel opens up and everything is fine. The problem is that we are using other programs as well such as Quickbooks that export to excel and t...

how do I add error bars to a 3D chart in excel?
The help states you can only add error bars to data series in 2D area. Is there a way to add them to a 3D chart? Hi, I would not have thought so. Obviously as it is not a built-in option the only way would be a work around perhaps using dummy series. Unfortunately you can create 3d combination charts. Stick with the 2d view. Cheers Andy elahe wrote: > The help states you can only add error bars to data series in 2D area. Is > there a way to add them to a 3D chart? -- Andy Pope, Microsoft MVP - Excel http://www.andypope.info I checked, and error bars are not offered for 3D ch...

q Emailing Excel Sheet With Outlook
I am trying to send a table from Excel within the body of an Outlook (lastest versions) to be sent as a fax. Am able to do this, BUT when the document prints out on the fax machine the formating is off (too big for the sheet). I am flexible on changing the method I send it to the fax machine, however it must be sent to the fax via macro. Below is the code I am using. Any help would be greatly appreciated. David Public Sub DoIt() 'On Error GoTo Handler Dim EmailAddress(0 To 2) As String Dim Count As Integer Dim N As Integer Dim sRec1(0) As String Dim sRec2(0 To 1) As...

I need to print a word in PDF from excel.
Hi, In my excel Macro, I update several values and then open a word linked with that excel. Finally what I need to do is to print that word to PDF. I already have a PDF Printer, so I just need the code to do it. Can anybody help me? Thanks in advance. Gast=F3n. Habilita la impresora predeterminada como la PDF y ya lo puedes imprimir a al formato deseado Gracias Francisco,=20 Tienes alg=FAn codigo para ello? gracias Repitiendo: Desde el panel de impresoras asigno primero la que me interesa y despues ejecuto mi macro desde el archivo excel asignando la instruccion sig: midefaultes = a...

How do I get Excell to sort dates that range from 1800 to 1900's
I have posted a cemetery survey on Excell spreadsheet. When I try to sort the birth dates or death dates in ascending or descending order the range of 1900 dates will sort but the 1800 dates fall after the 1900 and will not sort. Why? Is this inherit with this program? The WinXL default dates start with 31 December 1899, so earlier "dates" are interpreted as Text. You can use helper columns and text functions (LEFT(),RIGHT(),MID()) to put the Year, Month and Day in separate columns, then sort. Take a look here for additional workarounds: http://j-walk.com/ss/excel/files...

Business Portal should allow requisition to be added to issued PO
The printing of a PO changes the status of the PO from New to Released (signifying the release of the PO to the vendor). Once a PO has been released, it will not show as a PO you can add items to from business portal. The current design of the product only allows you to add to POs with a status of New. Adding an item to a Released PO should trigger a change order. ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not ...

formula or VBA
I need to search through a column checking condtions. If the conditions are met, then I want to enter the corresponding value in the column next to it into a different cell. Basically, I want to search column A and, if the conditions are met, put the value in B into C. Would this be easier via formula or code? And maybe some starting suggestions would be nice if you don't mind. -- Thanks, Jim in a formula in col b =if(cond,a1,"") using vba for each c in range("a1:a100") if cond then c.offset(0,1)=c next -- Don Guillett SalesAid Software donaldb@281.com "...

How to get to email from Word
Sorry to break the thread, but replying to the original thread now produces an error message :( The suggested changes don't make any difference to the essential premise that it all works as long as Outlook is running in the background. Stepping though the code has provided inconsistent results. It usually crashes at the line strEMail = Application.GetAddress("", strEMail, False, 1, , , True, True) when the address is selected from the dialog and you OK out of the dialog; but I have noticed that this call has produced crashes in other routines where Outlook is not running. Th...

Adding PST Tax onto Invoice Report
Hi there, Can anyone show me or help me start off in modifying the sales invoice report to display both GST and PST taxes for Canadian companies. I know that the report is within report writer but am clueless on how to start this off, but more on where I need to pull the data. Thanks. Hi Ian, This is fairly easy... you'll have to work with calculated fields and use the schdeduled tax table (TX_Detail_MSTR = TX00201). Normaly, those taxes are already taken care within the default SOP Blank Form, but I suspect that you want to show the various tax labels and their respec...

Effective VBA Code for Conditional Charting
Hello there, in a line chart, I need to show 3 different markers / colors for data points depending on whether the basic data to be shown are =, > or < zero. My attempts to code this in vba works, but very slowly. I suspect there is an effective way to do this, but can't find it. Does anyboday know better ? Thank you in advance, Kind regards, H.G. Lamy Hi H, Maybe you don't need VBA code at all. Have a look at Jon Peltier's examples on conditional charts. (http://www.geocities.com/jonpeltier/Excel/Charts/format.html#CondChart) You should be able to modify the techn...