这个怎么样:我使用该ColorIndex
属性通过从后面递增来设置单元格的颜色1
:
Dim dict As New Scripting.Dictionary
Sub ReadTextFile()
Dim fso As FileSystemObject, filePath As String, data As Variant, colorIndex As Integer
filePath = "C:\Users\Alex\Desktop\input.txt" //Change this
Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)
colorIndex = 1
Do While Not txtStream.AtEndOfStream
inputLine = txtStream.ReadLine
data = Split(inputLine, vbTab)
With Worksheets("Sheet1")
.Cells(CInt(data(0)), CInt(data(1))) = data(2)
.Cells(CInt(data(0)), CInt(data(1))).Interior.colorIndex = GetColor(CStr(data(2)), colorIndex)
End With
colorIndex = colorIndex + 1
Loop
txtStream.Close
End Sub
Function GetColor(label As String, colorIndex As Integer)
If Not dict.Exists(label) Then
dict.Add label, colorIndex
GetColor = colorIndex
Exit Function
Else
GetColor = dict(label)
End If
End Function
我唯一没有做的是添加图例,但我相信您可以遍历字典并写入工作表上您想要的任何位置。