2013-07-31 116 views
0

有人可以幫助我如何使用這個函數將excel文件中的數據轉換爲子文件中的XML文件?當我去創建一個宏時,默認情況下它已經爲sub創建了一個宏,但我需要將它作爲一個函數。我需要能夠使用這可能是工具欄上的自定義按鈕,或者我可以如何將它用於任何需要將它從Excel轉換爲XML文件的電子表格?如何在子函數中執行這個Excel到XML函數?

Public Function ExportToXML(FullPath As String, RowName _ 
As String) As Boolean 

On Error GoTo ErrorHandler 


Dim colIndex As Integer 
Dim rwIndex As Integer 
Dim asCols() As String 
Dim oWorkSheet As Worksheet 
Dim sName As String 
Dim lCols As Long, lRows As Long 
Dim iFileNum As Integer 


Set oWorkSheet = ThisWorkbook.Worksheets(1) 
sName = oWorkSheet.Name 
lCols = oWorkSheet.Columns.Count 
lRows = oWorkSheet.Rows.Count 


ReDim asCols(lCols) As String 

iFileNum = FreeFile 
Open FullPath For Output As #iFileNum 

For i = 0 To lCols - 1 
'Assumes no blank column names 
If Trim(Cells(1, i + 1).Value) = "" Then Exit For 
asCols(i) = Cells(1, i + 1).Value 
Next i 

If i = 0 Then GoTo ErrorHandler 
lCols = i 

Print #iFileNum, "<?xml version=""1.0""?>" 
Print #iFileNum, "<" & sName & ">" 
For i = 2 To lRows 
If Trim(Cells(i, 1).Value) = "" Then Exit For 
Print #iFileNum, "<" & RowName & ">" 

For j = 1 To lCols 

    If Trim(Cells(i, j).Value) <> "" Then 
     Print #iFileNum, " <" & asCols(j - 1) & "><![CDATA["; 
     Print #iFileNum, Trim(Cells(i, j).Value); 
     Print #iFileNum, "]]></" & asCols(j - 1) & ">" 
     DoEvents 'OPTIONAL 
    End If 
Next j 
Print #iFileNum, " </" & RowName & ">" 
Next i 

Print #iFileNum, "</" & sName & ">" 
ExportToXML = True 
ErrorHandler: 
If iFileNum > 0 Then Close #iFileNum 
Exit Function 
End Function 

回答

0

要轉換成可以從一個按鈕,你會改變它要運行的Sub

Public Sub ExportToXML() 

這將在最後一行自動切換到End Sub

FullPathRowName將不再作爲函數參數傳遞,因此可能需要從工作表上的單元格或兩個InputBoxes中讀取。

Sub不會再返回Boolean的值,所以不管這個值發生什麼,都必須在同一個Sub中轉換爲代碼(或者可能傳遞給另一個Sub)。