2013-10-20 187 views
0

我是VBA新手。我正在阅读制表符分隔的文件并解析它。 文件中的每一行包含一个行索引,山口索引和标签:例如:VBA excel根据txt文件输入填充单元格颜色

0 0 "John" 

1 1 "Lena" 

9 14 "John" 

我假设分配与彩色每个标签,并填充匹配[行,列]与分配的颜色。 标签可能出现在多个文件行中。 此外,我应该创建一个图例(在工作表上的不同位置),它描述了为每种颜色分配哪个标签。我看到一个新的标签,我检查这个标签是否存在于字典中,如果它存在,我使用它的现有颜色,如果没有,我添加一个新的条目到字典中。 在VB中做这件事的最好方法是什么?我应该使用什么数据结构来检查当前标签是否存在,如果存在,请使用它的颜色?

感谢, 李

+0

可以显示'.txt'文件的结构吗? –

+0

请看上面,谢谢。 – user429400

+1

词典在VBA中可用。早期绑定到'Microsoft Scripting Runtime'('scrrun.dll')或延迟绑定到'Scripting.Dictionary' –

回答

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 

我没有做过的唯一位添加图例,但我相信你可以遍历字典并写到工作表上的任何你想要的地方。

相关问题