2013-10-20 232 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 

我沒有做過的唯一位添加圖例,但我相信你可以遍歷字典並寫到工作表上的任何你想要的地方。

相關問題