4

这是我将 excel 单元格写入 XML 文件的主要函数的标题。我希望它调用另一个函数,它可以自己编写一套。

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)

这是第二个函数的开始,尽管我得到了“找不到对象”的错误。

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

我如何需要构造调用和/或变量以将打开的文件作为对象传递给第二个函数?

4

2 回答 2

7

您可以请求、存储和传递句柄,如下所示:

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)

Sub WriteCustomer(handle As Integer)
   Print #handle, "         <Customer>"
于 2013-06-25T14:15:22.603 回答
2

Since you have opened the file in the first function with the line

Open xmlFile For Output As #1

Any code that references #1 while it's open will write to the same file. Thus you can simply rewrite your second function as

Sub WriteCustomer()
  Print #1, "         <Customer>"
  Print #1, "             <First>" & 'Bill' & "</First>"
  Print #1, "             <Last>" & 'Johnson' & "</Last>"
  Print #1, "         </Customer>"
  Print #1, ""
End Sub
于 2013-06-25T14:05:46.473 回答