Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing one file with two functions in vba

This is the header of my main function to write excel cells to an XML file. I want this to call another function, which can do its own set of writing.

Public Sub WriteXML()
Dim Sheet As Worksheet
Dim Cell As Range
Dim xmlFile

xmlFile = ThisWorkbook.Path & "\" & 'Test1' & ".xml"

Set Sheet = ActiveWorkbook.Worksheets("Sht1")
Open xmlFile For Output As #1
    Print #1, "<?xml version=" & Chr(34) & "1.0" & Chr(34) & _
          " encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?>"
Call WriteCustomer(xmlFile)

This is the start of the second function, though I'm getting an 'object not found' sort of error.

Sub WriteCustomer(x As Variant)

Print x, "         <Customer>"
Print x, "             <First>" & 'Bill' & "</First>"
Print x, "             <Last>" & 'Johnson' & "</Last>"
Print x, "         </Customer>"
Print x, ""
End Sub

How do I need to construct the call and/or variable to pass the open file as an object to the second function?

like image 854
Glaucon Avatar asked Jan 14 '23 01:01

Glaucon


1 Answers

You can request, store and pass around a handle as follows:

Dim handle As Integer
handle = FreeFile()

Open xmlFile For Output As #handle
   Print #handle, "<?xml version=" & Chr(34) & "1.0" & Chr(34) & _

...
Call WriteCustomer(handle)

And

Sub WriteCustomer(handle As Integer)
   Print #handle, "         <Customer>"
like image 135
Alex K. Avatar answered Jan 16 '23 02:01

Alex K.