使用VBA写出跳过空白的XML文件

时间:2018-09-22 23:40:23

标签: excel xml vba

我正在Excel中使用vba来写出xml文件。我正在遍历并使用引用循环中单元格值的常量进行替换。我不能完全正确的是如何在单元格为空时跳过写出一段。我要跳过循环单元格a(i,3),如果引用的单元格为空,则不写该行,但是我想继续进行下一个替换。查看相关代码:

Const head = "<?xml version ""1.0"" encoding=""UTF-8""?>"
Const funct1 = "<Order function=""%%"" "
Const itemtype = "        <Item type=""%%"">"
Dim all
Dim xml As String, i As Long
Dim oPath As String: oPath = "C:\test\test.xml"
Dim intFF As Integer: intFF = FreeFile()
a = Range("A2:BU" & Cells(Rows.Count, 73).End(xlUp).Row)
xml = head
For i = 1 To UBound(a)
   xml = xml & vbNewLine & Replace(funct1, "%%", a(i, 3))
               vbNewLine & Replace(itemtype, "%%", a(i, 31))
Next
Open oPath For Output As #intFF
Print #intFF, xml
Close #intFF

Dim sBuf As String
Dim sTemp As String
Dim int2FF As Integer: int2FF = FreeFile()
Dim sFileName As String
sFileName = "C:\test\test.xml"
Open sFileName For Input As int2FF
Do Until EOF(int2FF)
    Line Input #int2FF, sBuf
    sTemp = sTemp & sBuf & vbCrLf
Loop
Close int2FF

1 个答案:

答案 0 :(得分:0)

在每个循环上测试字符数。如果字符计数= 0(Len(a(i, 3) = 0)),则转到下一个i。您将需要添加j作为计数器,并且只有在跳至XML语句时才递增。

Dim j As Long: j = 1

For i = 1 To UBound(a)
    If Len(a(i, 3)) <> 0 Then
        XML = XML & vbNewLine & Replace(funct1, "%%", a(i, 3)) _
        & vbNewLine & Replace(itemtype, "%%", a(i, 31))
        j = j + 1
    End If
Next