有人可以帮助我如何使用下面这个函数将excel文件中的数据转换为子文件中的XML文件吗?当我去创建一个宏时,它默认将它用于sub但我需要将它作为一个函数。我需要能够将其用作工具栏上的自定义按钮,或者如何将其用于将Excel从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 :(得分:0)
要转换为可以从按钮运行的Sub
,您可以将其更改为:
Public Sub ExportToXML()
这会自动将最后一行更改为End Sub
。
FullPath
和RowName
将不再作为函数参数传递,因此可能需要从工作表上的单元格中读取,或者可能从两个InputBoxes
中读取。 / p>
Sub将不再返回Boolean
值,因此无论此值发生什么,都必须转换为同一Sub中的代码(或者可能传递给另一个Sub)。