帮助嵌套如果/循环VBA

我正在循环一个Excel电子表格,并将所有的单元格合并为一个string,我做了。 现在我需要使用XML标签来格式化string,然后将其发送到上传文件中,并且正确地将标记工作到循环中有些困难。 看起来好像已经在工作了,但是其中一些标签并不在正确的位置。 任何帮助将非常感激。

码:

Public file As String Sub locate_file() Dim sheet1_95 As String Dim theRange As Range Dim strVal As String Dim wb As Workbook Dim counterDT As Integer Dim counterSVR As Integer Dim counterMB As Integer Dim outputStr As String 'prompt user for location of other excel sheet' file = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx") Set wb = Workbooks.Open(file) Dim cell As Range 'initializing the xml string' strVal = "<root>" Sheets("DT").Activate counterDT = 1 For Each cell In ActiveSheet.UsedRange.Cells 'this first if-block is just excluding the few header cells from the data collection' If cell.Value <> "SKU" And cell.Value <> "P Number" And cell.Value <> "Month" _ And cell.Value <> "DP Dmd" And cell.Value <> "Vertical" Then If cell.Column = "1" Then strVal = strVal & "<item><sku>" & cell.Value & "</sku>" ElseIf cell.Column = "2" Then strVal = strVal & "<pnum>" & cell.Value & "</pnum>" ElseIf cell.Column = "3" Then strVal = strVal & "<month>" & cell.Value & "</month>" ElseIf cell.Column = "4" Then strVal = strVal & "<forecast>" & cell.Value & "</forecast>" Else: strVal = strVal & "<vertical>" & cell.Value & "</vertical>" End If counterDT = counterDT + 1 If cell.Row <> 1 Then If counterDT Mod 6 = 0 Then strVal = "<item>" & strVal & "<percent>" & category.percent(cell, "DT") & "</percent>" Else: End If Else: End If End If Next strVal = strVal & "</root>" 

所以基本上问题是,这个循环/嵌套,如果是打印像30个“项目”标签在string的一开始,我不知道为什么。

对于其他一些信息,Excel工作表是6列,总是6。

当我创buildxml标签时,我喜欢将实际的标签移动到一个单独的函数中。 好处是它确保我的标签匹配。 缺点是你不能“应用”标签,直到结束。 在item和root之类的标签完成后,所有的标签都完成了。 这是一个例子:

 Sub locate_file() Dim sVal As String Dim sRow As String Dim wb As Workbook Dim sh As Worksheet Dim lCntDT As Long Dim rCell As Range Dim rRow As Range Dim vaTags As Variant gsFile = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx") If gsFile <> "False" Then Set wb = Workbooks.Open(gsFile) Set sh = wb.Sheets("DT") vaTags = Array("sku", "pnum", "month", "forecast", "vertical") lCntDT = 1 For Each rRow In sh.UsedRange.EntireRow sRow = "" If rRow.Cells(1) <> "SKU" Then For Each rCell In Intersect(sh.UsedRange, rRow).Cells If rCell.Column <= 4 Then sRow = sRow & TagValue(rCell.Value, vaTags(rCell.Column - 1)) Else sRow = sRow & TagValue(rCell.Value, vaTags(UBound(vaTags))) End If Next rCell lCntDT = lCntDT + 1 If rRow.Row <> 1 And lCntDT Mod 6 = 0 Then sVal = sVal & TagValue("CatPct", "percent") End If sRow = TagValue(sRow, "item") sVal = sVal & sRow & vbNewLine End If Next rRow sVal = TagValue(sVal, "root") End If Debug.Print sVal End Sub Function TagValue(ByVal sValue As String, ByVal sTag As String) As String TagValue = "<" & sTag & ">" & sValue & "</" & sTag & ">" End Function