我想遍歷一個串列并用它批量填充相關專案的模板,但我似乎無法弄清楚如何去做。我已經能夠遍歷所有資料,但不能遍歷相關專案組。
我在網上搜索了一個解決方案,但每個人都在遍歷所有行,但沒有按照下面的示例所示進行分組。
樣本資料
| SN | 日期 | 數量 | 課程 |
|---|---|---|---|
| 1 | 日期1 | 金額1 | 美國廣播公司 |
| 1 | 日期1 | 金額1 | 美國廣播公司 |
| 1 | 日期1 | 金額1 | 美國廣播公司 |
| 2 | 日期2 | 金額2 | 美國廣播公司 |
| 2 | 日期2 | 金額2 | 美國廣播公司 |
| 3 | 日期3 | 金額3 | 美國廣播公司 |
| 3 | 日期3 | 金額3 | 美國廣播公司 |
| 3 | 日期3 | 金額3 | 美國廣播公司 |
預期輸出應如下所示:
<ENTRY>
<COURSE> ABC </COURSE>
<Date> date1 </DATE> <AMOUNT> Amount1 </AMOUNT>
<Date> date1 </DATE> <AMOUNT> Amount1 </AMOUNT>
<Date> date1 </DATE> <AMOUNT> Amount1 </AMOUNT>
</ENTRY>
<ENTRY>
<COURSE> ABC </COURSE>
<Date> date2 </DATE> <AMOUNT> Amount2 </AMOUNT>
<Date> date2 </DATE> <AMOUNT> Amount2 </AMOUNT>
</ENTRY>
<ENTRY>
<COURSE> ABC </COURSE>
<Date> date3 </DATE> <AMOUNT> Amount3 </AMOUNT>
<Date> date3 </DATE> <AMOUNT> Amount3 </AMOUNT>
<Date> date3 </DATE> <AMOUNT> Amount3 </AMOUNT>
</ENTRY>
AND SO ON.....
如果需要進一步說明,請告訴我。
我不擅長 VBA,我只是想簡化我的作業。提前致謝。
uj5u.com熱心網友回復:
將每一行與上一行和下一行進行比較,以確定是組的開始還是結束。
Option Explicit
Sub macro1()
Dim ws As Worksheet
Dim r As Long, c As Long, lastrow As Long
Dim xml As String, tag As String
Set ws = Sheet1
With ws
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastrow
' start of group
If .Cells(r, 1) <> .Cells(r - 1, 1) Then
tag = .Cells(1, 4) & ">"
xml = xml & "<ENTRY>" & vbLf & _
"<" & tag & .Cells(r, 4) & "</" & tag & vbLf
End If
' data rows
For c = 2 To 3
tag = .Cells(1, c) & ">"
xml = xml & "<" & tag & _
.Cells(r, c) & "</" & tag
Next
xml = xml & vbLf
' end of group
If .Cells(r 1, 1) <> .Cells(r, 1) Then
xml = xml & "</ENTRY>" & vbLf
End If
Next
End With
xml = "<DATA>" & vbLf & xml & "</DATA>"
' output text file
Const XMLFILE = "output.xml"
Dim FSO As Object, ts As Object, filename As String
Set FSO = CreateObject("Scripting.FilesystemObject")
filename = ThisWorkbook.Path & "\" & XMLFILE
Set ts = FSO.createtextfile(filename, overwrite:=True, Unicode:=True)
ts.write xml
ts.Close
MsgBox "Done see " & filename, vbInformation
Shell "Notepad.exe " & filename, 1
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/396686.html
上一篇:比較串列的所有元素
下一篇:根據靠近運輸機的代理設定速度
