locked
Explain differences between styles of VBA coding RRS feed

  • Question

  • When I look for VBA examples to use (I'm trying to make a word document from within a VBA module that's part of an Access database), I often find contrasting styles. For instance, at http://support.microsoft.com/kb/316383, I find code that looks like this:

    Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
    
        Dim oWord As Word.Application
        Dim oDoc As Word.Document
        [...elided stuff...]
        'Start Word and open the document template.
        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oDoc = oWord.Documents.Add
    
    
    

    Notice that the assignment to oWord and oDoc are simple assignments -- the word "Set" does not appear.

    On the other hand, at http://msdn.microsoft.com/en-us/library/aa140082(office.10).aspx, I find this:

    Dim appWord As Word.Application
    Dim doc As Word.Document
    [...elided stuff...]
    
    On Error Resume Next
    Set appWord = GetObject(, "Word.application")
    If Err = 429 Then
    	Set appWord = New Word.Application
    	Err = 0
    End If
    
    With appWord
    	Set doc = .Documents(DOC_NAME) [...]
    
    
    

    In this case, the word "Set" is used to assign values to object variables.

    When I try to paste the first version into VBA, I get weird errors about "Invalid use of property" or something, so I'll go with the second one, but I have to ask:

    * Is the first one valid code, in some form? Are there option I could/should set to make it usable? I figure it comes from Microsoft's own documentation, so it's PROBABLY real code. (I'm beginning to suspect that the difference is VBA versus VB.Net)

    * If I want the (VBA) compiler to be rigorous about type-checking (yeah, I know you sometimes just HAVE to use a Variant!), are there options that I should be turning on? Right now I use "Option Compare Database" and "Option Explicit"

     

    Thanks in advance for any help.

    John

    • Moved by kleinma Friday, September 17, 2010 7:18 PM (From:Visual Basic Language)
    Friday, September 17, 2010 4:41 PM

Answers

  • The first code example you did was VB.NET code, while the second looks more VBA/VB6 style syntax.

    Set is not needed in .NET which is why you don't see it in the first example code.

    I am going to move this thread to the VBA forum.


    Matt Kleinwaks - MSMVP MSDN Forums Moderator - www.zerosandtheone.com
    • Marked as answer by Ji.Zhou Wednesday, September 22, 2010 8:13 AM
    Friday, September 17, 2010 7:18 PM