假设这个工作簿文件名是Book1.xlsm,可以点击开发 》 宏, 用下面的VBA:
Sub CreateTxt()
Dim xlsFile As String
xlsFileName = "Book1.xlsm"
xlsSheetName = "Sheet1"
Dim wsh As Worksheet
Set wsh = Workbooks(xlsFileName).Worksheets(xlsSheetName)
Dim xlsPath As String
xlsPath = Workbooks(xlsFileName).Path
Dim arr() As Variant
Dim nLines As Long
nLines = wsh.Range("A1000").End(xlUp).Row
arr = wsh.Range("A1:B" & nLines)
Dim dic As Object
Dim key As Variant
Set dic = CreateObject("Scripting.Dictionary")
Dim i As Long
With dic
For i = 1 To UBound(arr, 1)
If .Exists(arr(i, 1)) Then
.Item(arr(i, 1)) = .Item(arr(i, 1)) & "|" & arr(i, 2)
Else
.Add arr(i, 1), arr(i, 2)
End If
Next
End With
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
For Each key In dic
'Debug.Print key; "?? "; dic(key)
Set f = fso.OpenTextFile(xlsPath & "\" & key & ".txt", 2, True)
f.Write dic(key)
f.Close
Next
End Sub
其中下面两行里加粗斜体的部分请根据你的实际表格做更改:
xlsFileName = "Book1.xlsm"
nLines = wsh.Range("A1000").End(xlUp).Row
TXT文件生成的位置是你原Excel表格所在位置。