2013-06-25 21 views
1

這是將excel單元格寫入XML文件的主要函數的頭文件。我希望這可以調用另一個函數,它可以完成自己的一組寫作。用vba寫兩個函數的文件

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 

如何構建調用和/或變量以將打開的文件作爲對象傳遞給第二個函數?

+0

已打開該文件作爲# 1 - 所以你需要打印到#1,而不是xmlFile。 – Floris

回答

3

您可以要求,存儲和周圍句柄傳遞如下:

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>" 
+0

#在這方面也做了什麼? – Glaucon

1

既然你已經打開了文件中的第一功能與線

Open xmlFile For Output As #1 

引用#1,而它的開放將寫入同一個文件中的任何代碼。因此,你可以簡單地重寫你的第二個功能

Sub WriteCustomer() 
    Print #1, "   <Customer>" 
    Print #1, "    <First>" & 'Bill' & "</First>" 
    Print #1, "    <Last>" & 'Johnson' & "</Last>" 
    Print #1, "   </Customer>" 
    Print #1, "" 
End Sub