vb6parse 1.0.0

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="VB6Parse Library Reference - getobject - Objects">
    <title>getobject - Objects - VB6Parse Library Reference</title>
    <link rel="stylesheet" href="../../../assets/css/style.css">
    <link rel="stylesheet" href="../../../assets/css/docs-style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
    <script src="../../../assets/js/theme-switcher.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/vbnet.min.js"></script>
    <script>hljs.highlightAll();</script>
</head>
<body>
    <header class="docs-header">
        <div class="container">
            <h1><a href="../../../index.html">VB6Parse</a> / <a href="../../../library/index.html">Library</a> / <a href="../../../library/functions/objects/index.html">Objects</a> / getobject</h1>
            <p class="tagline">VB6 Library Reference</p>
        </div>
    </header>

    <nav class="docs-nav">
        <div class="container">
            <a href="../../../index.html">Home</a>
            <a href="../../../library/index.html">Library Reference</a>
            <a href="../../../documentation.html">Documentation</a>
            <a href="https://docs.rs/vb6parse" target="_blank">API Docs</a>
            <a href="https://github.com/scriptandcompile/vb6parse" target="_blank">GitHub</a>
            <button id="theme-toggle" class="theme-toggle" aria-label="Toggle theme">
                <span class="theme-icon">🌙</span>
            </button>
        </div>
    </nav>

    <main class="container">
        
        <article class="library-item">
            <p>GetObject Function
Returns a reference to an <code>ActiveX</code> object from a file or a running instance of an object.</p>
<h1 id="syntax">Syntax</h1>
<pre><code class="language-vbnet">GetObject([pathname] [, class])</code></pre>
<h1 id="parameters">Parameters</h1>
<ul>
<li><code>pathname</code> - Optional. <code>String</code> expression that specifies the full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.</li>
<li><code>class</code> - Optional. <code>String</code> expression that specifies the class of the object. The class argument uses the syntax <code>appname.objecttype</code> and has these parts:</li>
<li><code>appname</code> - Required. The name of the application providing the object.</li>
<li><code>objecttype</code> - Required. The type or class of object to create.</li>
</ul>
<h1 id="return-value">Return Value</h1>
<p>Returns an <code>Object</code> reference to the specified <code>ActiveX</code> object. The specific type depends on the class requested.</p>
<h1 id="remarks">Remarks</h1>
<ul>
<li>Use <code>GetObject</code> to access an existing <code>ActiveX</code> object from a file or to get a reference to a running instance of an application.</li>
<li>If pathname is omitted, <code>GetObject</code> returns a currently active object of the specified class.</li>
<li>If no instance of the object is running, an error occurs when pathname is omitted.</li>
<li>Some applications allow you to activate part of a file (e.g., <code>Excel</code> can activate a range in a workbook).</li>
<li>Use the <code>!</code> character in pathname to separate the file name from the part you want to activate: <code>"C:\MyDoc.xls!Sheet1!R1C1:R5C5"</code>.</li>
<li><code>GetObject</code> is useful when there is a current instance of the object or if you want to create the object with a file already loaded.</li>
<li>If there is no current instance and you don't want the object started with a file loaded, use <code>CreateObject</code>.</li>
<li>Once an object has been activated, you reference it in code using the object variable you defined.</li>
<li><code>GetObject</code> always returns a single instance. If you call <code>GetObject</code> multiple times, you may get different instances.</li>
<li>The object must support Automation for <code>GetObject</code> to work.</li>
</ul>
<h1 id="typical-uses">Typical Uses</h1>
<ul>
<li>Opening existing Office documents (<code>Excel</code>, <code>Word</code>, <code>PowerPoint</code>)</li>
<li>Getting references to running application instances</li>
<li>Accessing specific portions of files (<code>Excel</code> ranges, <code>Word</code> bookmarks)</li>
<li>Working with embedded or linked <code>OLE</code> objects</li>
<li>Automation of existing application instances</li>
<li>Document manipulation and data extraction</li>
</ul>
<h1 id="basic-usage-examples">Basic Usage Examples</h1>
<pre><code class="language-vbnet">&#x27; Get reference to Excel object from file
Dim xlApp As Object
Set xlApp = GetObject(&quot;C:\Reports\Sales.xls&quot;)
&#x27; Activate Excel
xlApp.Application.Visible = True
&#x27; Get existing Excel instance
Dim excelApp As Object
Set excelApp = GetObject(, &quot;Excel.Application&quot;)
&#x27; Get specific Excel range
Dim xlRange As Object
Set xlRange = GetObject(&quot;C:\Data\Report.xls!Sheet1!R1C1:R10C5&quot;)
&#x27; Get Word document
Dim wordDoc As Object
Set wordDoc = GetObject(&quot;C:\Documents\Letter.doc&quot;)</code></pre>
<h1 id="common-patterns">Common Patterns</h1>
<h2 id="1-get-or-create-pattern">1. Get or Create Pattern</h2>
<pre><code class="language-vbnet">Function GetExcelInstance() As Object
    On Error Resume Next
    &#x27; Try to get existing instance
    Set GetExcelInstance = GetObject(, &quot;Excel.Application&quot;)
    If Err.Number &lt;&gt; 0 Then
        &#x27; No instance running, create new one
        Set GetExcelInstance = CreateObject(&quot;Excel.Application&quot;)
    End If
    On Error GoTo 0
End Function
&#x27; Usage
Dim excel As Object
Set excel = GetExcelInstance()
excel.Visible = True</code></pre>
<h2 id="2-open-existing-excel-file">2. Open Existing Excel File</h2>
<pre><code class="language-vbnet">Sub ProcessExcelFile(filePath As String)
    Dim xlApp As Object
    Dim xlWorkbook As Object
    Dim xlSheet As Object
    On Error GoTo ErrorHandler
    &#x27; Open the Excel file
    Set xlWorkbook = GetObject(filePath)
    Set xlApp = xlWorkbook.Application
    &#x27; Make Excel visible
    xlApp.Visible = True
    &#x27; Access first worksheet
    Set xlSheet = xlWorkbook.Worksheets(1)
    &#x27; Process data
    Debug.Print xlSheet.Range(&quot;A1&quot;).Value
    &#x27; Cleanup
    xlWorkbook.Close SaveChanges:=False
    Set xlSheet = Nothing
    Set xlWorkbook = Nothing
    Set xlApp = Nothing
    Exit Sub
ErrorHandler:
    MsgBox &quot;Error: &quot; &amp; Err.Description
End Sub</code></pre>
<h2 id="3-access-specific-excel-range">3. Access Specific Excel Range</h2>
<pre><code class="language-vbnet">Sub ReadExcelRange()
    Dim xlRange As Object
    Dim cell As Variant
    On Error GoTo ErrorHandler
    &#x27; Get specific range from Excel file
    Set xlRange = GetObject(&quot;C:\Data\Sales.xls!Sheet1!R1C1:R10C3&quot;)
    &#x27; Loop through cells
    For Each cell In xlRange.Cells
        Debug.Print cell.Value
    Next cell
    &#x27; Cleanup
    xlRange.Parent.Parent.Close SaveChanges:=False
    Set xlRange = Nothing
    Exit Sub
ErrorHandler:
    MsgBox &quot;Error reading range: &quot; &amp; Err.Description
End Sub</code></pre>
<h2 id="4-connect-to-running-application">4. Connect to Running Application</h2>
<pre><code class="language-vbnet">Function ConnectToRunningWord() As Object
    On Error Resume Next
    Set ConnectToRunningWord = GetObject(, &quot;Word.Application&quot;)
    If Err.Number &lt;&gt; 0 Then
        MsgBox &quot;Word is not currently running&quot;
        Set ConnectToRunningWord = Nothing
    End If
    On Error GoTo 0
End Function
&#x27; Usage
Sub UseRunningWord()
    Dim wordApp As Object
    Set wordApp = ConnectToRunningWord()
    If Not wordApp Is Nothing Then
        Debug.Print &quot;Word has &quot; &amp; wordApp.Documents.Count &amp; &quot; documents open&quot;
        Set wordApp = Nothing
    End If
End Sub</code></pre>
<h2 id="5-multiple-file-processing">5. Multiple File Processing</h2>
<pre><code class="language-vbnet">Sub ProcessMultipleExcelFiles()
    Dim files() As String
    Dim i As Long
    Dim xlWorkbook As Object
    Dim xlApp As Object
    files = Array(&quot;C:\Data\Jan.xls&quot;, &quot;C:\Data\Feb.xls&quot;, &quot;C:\Data\Mar.xls&quot;)
    For i = LBound(files) To UBound(files)
        On Error Resume Next
        Set xlWorkbook = GetObject(files(i))
        If Err.Number = 0 Then
            Set xlApp = xlWorkbook.Application
            &#x27; Process workbook
            Debug.Print &quot;Processing: &quot; &amp; xlWorkbook.Name
            Debug.Print &quot;Sheets: &quot; &amp; xlWorkbook.Worksheets.Count
            &#x27; Close without saving
            xlWorkbook.Close SaveChanges:=False
        Else
            Debug.Print &quot;Failed to open: &quot; &amp; files(i)
        End If
        Set xlWorkbook = Nothing
        Set xlApp = Nothing
        On Error GoTo 0
    Next i
End Sub</code></pre>
<h2 id="6-word-document-automation">6. Word Document Automation</h2>
<pre><code class="language-vbnet">Sub ModifyWordDocument(filePath As String)
    Dim wordDoc As Object
    Dim wordApp As Object
    On Error GoTo ErrorHandler
    &#x27; Open existing Word document
    Set wordDoc = GetObject(filePath)
    Set wordApp = wordDoc.Application
    &#x27; Make Word visible
    wordApp.Visible = True
    &#x27; Modify document
    wordDoc.Content.InsertAfter vbCrLf &amp; &quot;Added text: &quot; &amp; Now
    &#x27; Save and close
    wordDoc.Save
    wordDoc.Close
    &#x27; Cleanup
    Set wordDoc = Nothing
    Set wordApp = Nothing
    Exit Sub
ErrorHandler:
    MsgBox &quot;Error modifying document: &quot; &amp; Err.Description
End Sub</code></pre>
<h2 id="7-excel-data-extraction">7. Excel Data Extraction</h2>
<pre><code class="language-vbnet">Function ExtractExcelData(filePath As String, _
                         sheetName As String, _
                         rangeName As String) As Variant
    Dim xlWorkbook As Object
    Dim xlSheet As Object
    Dim data As Variant
    On Error GoTo ErrorHandler
    Set xlWorkbook = GetObject(filePath)
    Set xlSheet = xlWorkbook.Worksheets(sheetName)
    &#x27; Get data from range
    data = xlSheet.Range(rangeName).Value
    &#x27; Close workbook
    xlWorkbook.Close SaveChanges:=False
    &#x27; Return data
    ExtractExcelData = data
    &#x27; Cleanup
    Set xlSheet = Nothing
    Set xlWorkbook = Nothing
    Exit Function
ErrorHandler:
    ExtractExcelData = Null
    If Not xlWorkbook Is Nothing Then xlWorkbook.Close SaveChanges:=False
End Function
&#x27; Usage
Sub DisplayData()
    Dim data As Variant
    data = ExtractExcelData(&quot;C:\Reports\Sales.xls&quot;, &quot;Summary&quot;, &quot;A1:C10&quot;)
    If Not IsNull(data) Then
        Debug.Print &quot;Data extracted: &quot; &amp; UBound(data, 1) &amp; &quot; rows&quot;
    End If
End Sub</code></pre>
<h2 id="8-application-instance-manager">8. Application Instance Manager</h2>
<pre><code class="language-vbnet">Type AppInstance
    AppName As String
    ProgID As String
    IsRunning As Boolean
    Instance As Object
End Type
Function CheckAppInstance(progID As String) As AppInstance
    Dim result As AppInstance
    result.ProgID = progID
    result.AppName = Split(progID, &quot;.&quot;)(0)
    On Error Resume Next
    Set result.Instance = GetObject(, progID)
    On Error GoTo 0
    result.IsRunning = Not (result.Instance Is Nothing)
    CheckAppInstance = result
End Function
Sub ReportRunningApplications()
    Dim apps() As String
    Dim i As Long
    Dim instance As AppInstance
    apps = Array(&quot;Excel.Application&quot;, &quot;Word.Application&quot;, _
                 &quot;PowerPoint.Application&quot;, &quot;Outlook.Application&quot;)
    For i = LBound(apps) To UBound(apps)
        instance = CheckAppInstance(apps(i))
        If instance.IsRunning Then
            Debug.Print instance.AppName &amp; &quot; is running&quot;
        Else
            Debug.Print instance.AppName &amp; &quot; is not running&quot;
        End If
    Next i
End Sub</code></pre>
<h2 id="9-safe-object-retrieval">9. Safe Object Retrieval</h2>
<pre><code class="language-vbnet">Function SafeGetObject(Optional filePath As Variant, _
                      Optional progID As Variant) As Object
    Dim obj As Object
    On Error Resume Next
    If IsMissing(filePath) And IsMissing(progID) Then
        &#x27; Invalid call
        Set SafeGetObject = Nothing
        Exit Function
    End If
    If IsMissing(filePath) Then
        &#x27; Get running instance
        Set obj = GetObject(, CStr(progID))
    ElseIf IsMissing(progID) Then
        &#x27; Get from file
        Set obj = GetObject(CStr(filePath))
    Else
        &#x27; Get from file with specific class
        Set obj = GetObject(CStr(filePath), CStr(progID))
    End If
    If Err.Number &lt;&gt; 0 Then
        Debug.Print &quot;GetObject failed: &quot; &amp; Err.Description
        Set obj = Nothing
    End If
    On Error GoTo 0
    Set SafeGetObject = obj
End Function</code></pre>
<h2 id="10-document-comparison">10. Document Comparison</h2>
<pre><code class="language-vbnet">Function CompareExcelFiles(file1 As String, file2 As String) As Boolean
    Dim wb1 As Object
    Dim wb2 As Object
    Dim sheet1 As Object
    Dim sheet2 As Object
    Dim identical As Boolean
    On Error GoTo ErrorHandler
    Set wb1 = GetObject(file1)
    Set wb2 = GetObject(file2)
    &#x27; Compare sheet counts
    If wb1.Worksheets.Count &lt;&gt; wb2.Worksheets.Count Then
        CompareExcelFiles = False
        GoTo Cleanup
    End If
    &#x27; Compare first sheet data
    Set sheet1 = wb1.Worksheets(1)
    Set sheet2 = wb2.Worksheets(1)
    If sheet1.UsedRange.Address = sheet2.UsedRange.Address Then
        identical = True
    Else
        identical = False
    End If
    CompareExcelFiles = identical
Cleanup:
    wb1.Close SaveChanges:=False
    wb2.Close SaveChanges:=False
    Set sheet1 = Nothing
    Set sheet2 = Nothing
    Set wb1 = Nothing
    Set wb2 = Nothing
    Exit Function
ErrorHandler:
    CompareExcelFiles = False
    If Not wb1 Is Nothing Then wb1.Close SaveChanges:=False
    If Not wb2 Is Nothing Then wb2.Close SaveChanges:=False
End Function</code></pre>
<h1 id="advanced-usage">Advanced Usage</h1>
<h2 id="1-document-manager-class">1. Document Manager Class</h2>
<pre><code class="language-vbnet">&#x27; Class: DocumentManager
Private m_FilePath As String
Private m_Document As Object
Private m_Application As Object
Private m_DocumentType As String
Public Sub OpenDocument(filePath As String)
    On Error GoTo ErrorHandler
    m_FilePath = filePath
    Set m_Document = GetObject(filePath)
    Set m_Application = m_Document.Application
    &#x27; Determine document type
    m_DocumentType = TypeName(m_Document)
    Exit Sub
ErrorHandler:
    Err.Raise vbObjectError + 1000, , &quot;Failed to open: &quot; &amp; filePath
End Sub
Public Property Get IsOpen() As Boolean
    IsOpen = Not (m_Document Is Nothing)
End Property
Public Property Get DocumentType() As String
    DocumentType = m_DocumentType
End Property
Public Sub MakeVisible()
    If Not m_Application Is Nothing Then
        m_Application.Visible = True
    End If
End Sub
Public Function GetProperty(propertyName As String) As Variant
    On Error Resume Next
    GetProperty = CallByName(m_Document, propertyName, VbGet)
End Function
Public Sub CloseDocument(Optional saveChanges As Boolean = False)
    If Not m_Document Is Nothing Then
        m_Document.Close saveChanges
        Set m_Document = Nothing
        Set m_Application = Nothing
    End If
End Sub
Private Sub Class_Terminate()
    CloseDocument False
End Sub</code></pre>
<h2 id="2-batch-file-processor">2. Batch File Processor</h2>
<pre><code class="language-vbnet">Type ProcessingResult
    FileName As String
    Success As Boolean
    ErrorMessage As String
    ProcessedDate As Date
End Type
Function BatchProcessFiles(files As Collection, _
                          processingFunc As String) As Collection
    Dim results As New Collection
    Dim file As Variant
    Dim doc As Object
    Dim result As ProcessingResult
    For Each file In files
        result.FileName = CStr(file)
        result.ProcessedDate = Now
        On Error Resume Next
        Set doc = GetObject(CStr(file))
        If Err.Number = 0 Then
            &#x27; Call custom processing function
            Application.Run processingFunc, doc
            doc.Save
            doc.Close
            result.Success = True
            result.ErrorMessage = &quot;&quot;
        Else
            result.Success = False
            result.ErrorMessage = Err.Description
        End If
        On Error GoTo 0
        Set doc = Nothing
        results.Add result
    Next file
    Set BatchProcessFiles = results
End Function</code></pre>
<h2 id="3-smart-office-connector">3. Smart Office Connector</h2>
<pre><code class="language-vbnet">Class OfficeConnector
    Private m_Instances As Collection
    Private Sub Class_Initialize()
        Set m_Instances = New Collection
    End Sub
    Public Function GetOrCreateExcel() As Object
        Dim excel As Object
        Dim key As String
        key = &quot;Excel.Application&quot;
        &#x27; Check cache
        On Error Resume Next
        Set excel = m_Instances(key)
        On Error GoTo 0
        If excel Is Nothing Then
            &#x27; Try to get existing instance
            On Error Resume Next
            Set excel = GetObject(, key)
            On Error GoTo 0
            If excel Is Nothing Then
                &#x27; Create new instance
                Set excel = CreateObject(key)
            End If
            &#x27; Cache instance
            m_Instances.Add excel, key
        End If
        Set GetOrCreateExcel = excel
    End Function
    Public Function OpenFile(filePath As String) As Object
        Dim doc As Object
        On Error GoTo ErrorHandler
        Set doc = GetObject(filePath)
        Set OpenFile = doc
        Exit Function
    ErrorHandler:
        Set OpenFile = Nothing
    End Function
    Public Sub CloseAll()
        Dim item As Variant
        For Each item In m_Instances
            On Error Resume Next
            item.Quit
            On Error GoTo 0
        Next item
        Set m_Instances = New Collection
    End Sub
    Private Sub Class_Terminate()
        CloseAll
    End Sub
End Class</code></pre>
<h2 id="4-document-cache-system">4. Document Cache System</h2>
<pre><code class="language-vbnet">Type CachedDocument
    FilePath As String
    Document As Object
    LastAccessed As Date
    AccessCount As Long
End Type
Private m_DocumentCache As Collection
Private Const CACHE_TIMEOUT = 300 &#x27; 5 minutes in seconds
Sub InitializeDocumentCache()
    Set m_DocumentCache = New Collection
End Sub
Function GetCachedDocument(filePath As String) As Object
    Dim cached As CachedDocument
    Dim i As Long
    Dim found As Boolean
    &#x27; Search cache
    For i = 1 To m_DocumentCache.Count
        cached = m_DocumentCache(i)
        If cached.FilePath = filePath Then
            &#x27; Check if cache is still valid
            If DateDiff(&quot;s&quot;, cached.LastAccessed, Now) &lt; CACHE_TIMEOUT Then
                cached.LastAccessed = Now
                cached.AccessCount = cached.AccessCount + 1
                m_DocumentCache.Remove i
                m_DocumentCache.Add cached, filePath
                Set GetCachedDocument = cached.Document
                Exit Function
            Else
                &#x27; Cache expired, remove it
                cached.Document.Close SaveChanges:=False
                m_DocumentCache.Remove i
                Exit For
            End If
        End If
    Next i
    &#x27; Not in cache, open new
    On Error Resume Next
    Set cached.Document = GetObject(filePath)
    On Error GoTo 0
    If Not cached.Document Is Nothing Then
        cached.FilePath = filePath
        cached.LastAccessed = Now
        cached.AccessCount = 1
        m_DocumentCache.Add cached, filePath
        Set GetCachedDocument = cached.Document
    Else
        Set GetCachedDocument = Nothing
    End If
End Function
Sub ClearDocumentCache()
    Dim cached As CachedDocument
    Dim i As Long
    For i = m_DocumentCache.Count To 1 Step -1
        cached = m_DocumentCache(i)
        cached.Document.Close SaveChanges:=False
        m_DocumentCache.Remove i
    Next i
End Sub</code></pre>
<h1 id="error-handling">Error Handling</h1>
<pre><code class="language-vbnet">Function SafelyGetObject(Optional pathName As String, _
                        Optional className As String) As Object
    On Error GoTo ErrorHandler
    If pathName &lt;&gt; &quot;&quot; And className &lt;&gt; &quot;&quot; Then
        Set SafelyGetObject = GetObject(pathName, className)
    ElseIf pathName &lt;&gt; &quot;&quot; Then
        Set SafelyGetObject = GetObject(pathName)
    ElseIf className &lt;&gt; &quot;&quot; Then
        Set SafelyGetObject = GetObject(, className)
    Else
        Set SafelyGetObject = Nothing
    End If
    Exit Function
ErrorHandler:
    Select Case Err.Number
        Case 429  &#x27; ActiveX component can&#x27;t create object
            Debug.Print &quot;Object unavailable or not registered&quot;
        Case 432  &#x27; File name or class name not found
            Debug.Print &quot;File or class not found: &quot; &amp; pathName &amp; &quot; &quot; &amp; className
        Case 462  &#x27; Remote server machine does not exist
            Debug.Print &quot;Server not available&quot;
        Case 70   &#x27; Permission denied
            Debug.Print &quot;Access denied&quot;
        Case Else
            Debug.Print &quot;Error &quot; &amp; Err.Number &amp; &quot;: &quot; &amp; Err.Description
    End Select
    Set SafelyGetObject = Nothing
End Function</code></pre>
<p>Common errors:
- <strong>Error 429</strong>: <code>ActiveX</code> component can't create object - object not available or not registered.
- <strong>Error 432</strong>: File name or class name not found during Automation operation.
- <strong>Error 462</strong>: Remote server machine does not exist or is unavailable.
- <strong>Error 70</strong>: Permission denied - file is locked or insufficient permissions.
- <strong>Error 5</strong>: Invalid procedure call - incorrect parameters.</p>
<h1 id="performance-considerations">Performance Considerations</h1>
<ul>
<li><code>GetObject</code> can be slower than <code>CreateObject</code> for new instances</li>
<li>Opening files with <code>GetObject</code> loads the entire file into memory</li>
<li>Use specific ranges when possible to minimize memory usage</li>
<li>Consider caching object references for frequently accessed files</li>
<li>Close objects when done to free resources</li>
<li>For batch operations, reuse application instances</li>
</ul>
<h1 id="best-practices">Best Practices</h1>
<ol>
<li><strong>Always use error handling</strong> - files may not exist or be accessible</li>
<li><strong>Close objects explicitly</strong> - release resources promptly</li>
<li><strong>Set object variables to Nothing</strong> - ensure cleanup</li>
<li><strong>Check if object is Nothing</strong> before using</li>
<li><strong>Use specific object types</strong> when possible (late vs early binding)</li>
<li><strong>Handle both file and instance retrieval</strong> scenarios</li>
<li><strong>Cache references</strong> for frequently accessed objects</li>
<li><strong>Test file existence</strong> before calling <code>GetObject</code></li>
</ol>
<h1 id="comparison-with-other-functions">Comparison with Other Functions</h1>
<h2 id="getobject-vs-createobject"><code>GetObject</code> vs <code>CreateObject</code></h2>
<pre><code class="language-vbnet">&#x27; GetObject - Get existing instance or open file
Set excel = GetObject(, &quot;Excel.Application&quot;)  &#x27; Gets running instance
Set workbook = GetObject(&quot;C:\Data.xls&quot;)       &#x27; Opens existing file
&#x27; CreateObject - Always creates new instance
Set excel = CreateObject(&quot;Excel.Application&quot;) &#x27; Creates new instance
Set workbook = excel.Workbooks.Open(&quot;C:\Data.xls&quot;) &#x27; Opens file</code></pre>
<h2 id="getobject-with-file-vs-without"><code>GetObject</code> with File vs Without</h2>
<pre><code class="language-vbnet">&#x27; With file - Opens the file
Set doc = GetObject(&quot;C:\Report.xls&quot;)
&#x27; Without file - Gets running instance
Set app = GetObject(, &quot;Excel.Application&quot;)
&#x27; With both - Opens file with specific application
Set doc = GetObject(&quot;C:\Data.txt&quot;, &quot;Excel.Application&quot;)</code></pre>
<h1 id="limitations">Limitations</h1>
<ul>
<li>Requires the object to support Automation</li>
<li>File must exist for pathname-based calls</li>
<li>Application must be registered on the system</li>
<li>May fail if file is already open exclusively</li>
<li>Limited control over how the file is opened</li>
<li>Cannot specify detailed options (read-only, etc.)</li>
<li>Not all file types support the <code>!</code> notation for partial activation</li>
<li>May behave differently across Office versions</li>
</ul>
<h1 id="file-activation-syntax">File Activation Syntax</h1>
<p>For files that support partial activation:</p>
<pre><code class="language-vbnet">&#x27; Excel - specific range
Set range = GetObject(&quot;C:\Data.xls!Sheet1!R1C1:R10C10&quot;)
&#x27; Excel - named range
Set range = GetObject(&quot;C:\Data.xls!MyRange&quot;)
&#x27; Word - bookmark (if supported)
Set bookmark = GetObject(&quot;C:\Doc.doc!MyBookmark&quot;)</code></pre>
<h1 id="related-functions">Related Functions</h1>
<ul>
<li><code>CreateObject</code> - Creates a new instance of an <code>ActiveX</code> object</li>
<li><code>GetAutoServerSettings</code> - Returns <code>DCOM</code> server security settings</li>
<li><code>CallByName</code> - Calls a method or accesses a property dynamically</li>
<li><code>TypeName</code> - Returns type information about an object</li>
<li><code>IsObject</code> - Checks if a variable contains an object reference</li>
<li><code>Set</code> - Assigns an object reference to a variable</li>
</ul>
        </article>
        
        <div style="margin-top: 3rem; padding-top: 2rem; border-top: 1px solid var(--border-color);">
            <p>
                <a href="index.html">← Back to Objects</a> |
                <a href="../index.html">View all functions</a>
            </p>
        </div>

    </main>

    <footer>
        <div class="container">
            <p>&copy; 2024-2026 VB6Parse Contributors. Licensed under the MIT License.</p>
        </div>
    </footer>
</body>
</html>