0

有人可以帮助我如何使用下面的这个函数将我的 excel 文件中的数据转换为 sub 中的 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
4

1 回答 1

0

要转换为Sub可以从按钮运行的,您可以将其更改为:

Public Sub ExportToXML()

这将自动将最后一行更改为End Sub.

FullPath并且RowName将不再作为函数参数传递,因此可能需要从工作表上的单元格中读取,或者可能从两个InputBoxes.

Sub 将不再返回Boolean值,因此无论该值发生什么,都必须将其转换为同一 Sub 中的代码(或可能传递给另一个 Sub)。

于 2013-08-01T00:02:52.357 回答