Consulting

Results 1 to 6 of 6

Thread: How to make this code to work in VB

  1. #1
    VBAX Newbie
    Joined
    Mar 2006
    Posts
    5
    Location

    How to make this code to work in VB

    How to make this code work in VB. This code works fine when used as Macro but when I put the same code in VB it doesnot.Can anybody help me out?



    Option Explicit

    Sub AddTable()

    Dim Tbl As Table

    Set Tbl = ActiveDocument.Tables.Add(Range:=Selection.Range, _
    NumRows:=4, NumColumns:=2)
    Tbl.Range.Font.Bold = True
    Tbl.Cell(1, 1).Range.Text = "AAA"
    Tbl.Cell(1, 2).Range.Text = "111"

    End Sub

  2. #2
    VBAX Expert
    Joined
    Jul 2004
    Location
    Wilmington, DE
    Posts
    600
    Location
    If you're trying to run this in VB, you will need to set a reference to the Word library, and probably set a variable to the Word.Application object:

    [VBA]
    Option Explicit

    Sub AddTable()

    Dim wdApp As Word.Application
    Dim Tbl As Table

    Set wdApp = New Word.Application
    Set Tbl = wdApp.ActiveDocument.Tables.Add(Range:=Selection.Range, _
    NumRows:=4, NumColumns:=2)
    With Tbl
    .Range.Font.Bold = True
    .Cell(1, 1).Range.Text = "AAA"
    .Cell(1, 2).Range.Text = "111"
    End With

    End Sub
    [/VBA]
    Regards,

    Patrick

    I wept for myself because I had no PivotTable.

    Then I met a man who had no AutoFilter.

    Microsoft MVP for Excel, 2007 & 2008

  3. #3
    VBAX Master Killian's Avatar
    Joined
    Nov 2004
    Location
    London
    Posts
    1,132
    Location
    Hi nishant,

    I think you may be having problems because you're using late-binding and don't have a reference set to the Word Object Model.

    So if you use your existing code to create the Word app and document, the method posted above should work fine - but when you declare the variable "Tbl", it must be as an Object rather than a Word.Table[VBA]Dim Tbl as Object[/VBA]
    K :-)

  4. #4
    VBAX Regular
    Joined
    Jul 2007
    Posts
    16
    Location
    i found this helpful, thanks

  5. #5
    VBAX Master Norie's Avatar
    Joined
    Jan 2005
    Location
    Stirling, Scotland
    Posts
    1,831
    Location
    This means nothing in VB.
    [vba]
    Range:=Selection.Range, _
    NumRows:=4, NumColumns:=2[/vba]
    Like the other members are suggesting, I think anyway, you need to properly reference objects like Range.

  6. #6
    VBAX Wizard
    Joined
    May 2004
    Posts
    6,713
    Location
    Actually, we don't know if the OP is using late-binding, or not - although it sort of looks more like it is early-binding.

    In any case nishant, the verdict is in. You need to clarify and set proper references to make your code work. Perhaps we can help if you post the code you are using to make the document itself.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •