Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VBA excel根据txt文件输入填充单元格颜色_Excel_Vba - Fatal编程技术网

VBA excel根据txt文件输入填充单元格颜色

VBA excel根据txt文件输入填充单元格颜色,excel,vba,Excel,Vba,我是VBA新手。我正在读取一个以制表符分隔的文件并对其进行分析。 文件中的每一行都包含一个行索引、一个列索引和一个标签:例如: 0 0 "John" 1 1 "Lena" 9 14 "John" 我假设为每个标签指定一种颜色,并用指定的颜色填充匹配的[row,col]。 标签可能出现在多个文件行中。 此外,我应该创建一个图例(在工作表的另一个位置),描述为每种颜色指定的标签 在c#中,我会使用字典:当我看到一个新标签时,我会检查该标签是否存在于字典中,如果

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

0    0    "John"

1    1    "Lena"

9    14   "John"
我假设为每个标签指定一种颜色,并用指定的颜色填充匹配的[row,col]。 标签可能出现在多个文件行中。 此外,我应该创建一个图例(在工作表的另一个位置),描述为每种颜色指定的标签

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

谢谢,
Li

这样如何:我使用
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

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

您可以显示
.txt
文件的结构吗?请参见上面的内容,谢谢。字典在VBA中提供。早期绑定到Microsoft脚本运行时(
scrrun.dll
)或晚期绑定到
Scripting.Dictionary
将有多少不同的标签?你知道吗?