尝试使用VBA在Excel中存储文本文件中的唯一string

我有一个问题,我的循环input一个string到Excel中。 我从一个可以是任意长度的文本文件中提取数据,但是到目前为止我所使用的所有数据都在100行数据和50000行数据之间。 我试图提取的string是4个字符,通常是数字,但可以是字母数字。 默认情况下,字符是0001,0002,0003和0004,但是如果他们select使用其他4个字符,这完全取决于我们的客户。 在Excel中input数据时,我只想input唯一的值。

整个代码可以给,但一切工作正常,所以我不认为这是必要的。 如果你这么认为,请求,我会编辑它。请记住,我已经尝试了许多不同的尝试在这个和逻辑似乎从来没有解决。

结果是包含文本文件中每个值的一长串行。

如果我不得不猜测,这是由于string是一个数字,然后excel存储为“2”而不是“0002”,所以我已经格式化整个列显示4个字符。 即使这样,我认为Excel将它视为“2”,所以string从不匹配数据。

任何帮助表示赞赏。

FileName = Application.GetOpenFilename() Open FileName For Input As #1 strSearch = "MTRDT" Do Until EOF(1) Line Input #1, ReadData If Left(ReadData, Len(strSearch)) = strSearch Then MtrdtCount = MtrdtCount + 1 MeterType = Mid(ReadData, 78, 4) lastrow = Cells(Rows.Count, "G").End(xlUp).Row + 1 MeterTypeTest = True For Each cell In Range("G3:G" & lastrow) If MeterType = cell.Value Then MeterTypeTest = False Exit For End If Next cell If MeterTypeTest = True Then Range("G" & MeterTypeCnt) = MeterType MeterTypeCnt = MeterTypeCnt + 1 End If Else End If Loop 

如果您使用所示的方法input了所有的数据,那么Excel将不会将input的数据看作是0002如数字2 – 它将被视为string"0002"

但是,您正在testing这些值与"'" & Mid(ReadData, 78, 4) ,这意味着您将比较"0002""'0002"

在input数据到单元格时,您需要添加该字符,而不是在进行比较之前。 所以以下应该工作:

 FileName = Application.GetOpenFilename() Open FileName For Input As #1 strSearch = "MTRDT" Do Until EOF(1) Line Input #1, ReadData If Left(ReadData, Len(strSearch)) = strSearch Then MtrdtCount = MtrdtCount + 1 MeterType = Mid(ReadData, 78, 4) lastrow = Cells(Rows.Count, "G").End(xlUp).Row + 1 MeterTypeTest = True For Each cell In Range("G3:G" & lastrow) If MeterType = cell.Value Then MeterTypeTest = False Exit For End If Next cell If MeterTypeTest Then Range("G" & MeterTypeCnt) = "'" & MeterType MeterTypeCnt = MeterTypeCnt + 1 End If End If Loop 

我认为将列“G”的numberformatLocal设置为下图

 Columns("g").NumberFormatLocal = "@" Filename = Application.GetOpenFilename() Open Filename For Input As #1 strSearch = "MTRDT" Do Until EOF(1) Line Input #1, ReadData If Left(ReadData, Len(strSearch)) = strSearch Then MtrdtCount = MtrdtCount + 1 MeterType = Mid(ReadData, 78, 4) lastrow = Cells(Rows.Count, "G").End(xlUp).Row + 1 MeterTypeTest = True For Each cell In Range("G3:G" & lastrow) If MeterType = cell.Value Then MeterTypeTest = False Exit For End If Next cell If MeterTypeTest = True Then Range("G" & MeterTypeCnt) = MeterType MeterTypeCnt = MeterTypeCnt + 1 End If Else End If Loop