0

我是 VBA 新手。我正在阅读一个制表符分隔的文件并对其进行解析。文件中的每一行都包含一个行索引、一个列索引和一个标签:例如:

0    0    "John"

1    1    "Lena"

9    14   "John"

我想为每个标签分配一种颜色,并用分配的颜色填充匹配的 [row,col]。一个标签可能出现在多个文件行中。此外,我应该创建一个图例(在工作表的不同位置),描述分配给每种颜色的标签。

在 c# 中,我会使用字典:当我看到一个新标签时,我会检查该标签是否存在于字典中,如果存在,则使用其现有颜色,如果不存在,则将新条目添加到字典中。在 VB 中执行此操作的最佳方法是什么?我应该使用什么数据结构来检查当前标签是否存在,如果存在,使用它的颜色?

谢谢,李

4

1 回答 1

0

这个怎么样:我使用该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

我唯一没有做的是添加图例,但我相信您可以遍历字典并写入工作表上您想要的任何位置。

于 2013-10-21T20:00:56.813 回答