我如何迭代一个特定的列?

我有一个Excel表,其中列AI有整数值。
我不知道我有多less价值。
我不知道每个值之间是否有空格。
有值重复。

A -------- 1| 76 2| 56 3| 34 4| ---- 5| 9 6| 9 .| --- .| --- .| 56 

我需要在文件.txt上写入所有没有重复的值。

我如何在VBA中编码?

像这样的东西应该让你在那里。

在你的VBA IDE进入工具菜单并select参考。 为ADODBlogging集select“Microstoft ActiveX数据对象2.8库”。

在你的VBA IDE进入工具菜单并select参考。 为您的文件输出select“Microsoft脚本运行时”。

 Private Sub CommandButton1_Click() Dim rs As New ADODB.Recordset Dim ws As Excel.Worksheet Set ws = ActiveWorkbook.Sheets("Sheet1") Dim lastRow As Long Dim lRow As Long Dim ts As TextStream Dim fs As FileSystemObject 'Create the text file to write to Set fs = New FileSystemObject Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False) 'Add fields to your recordset for storing data. With rs .Fields.Append "Value", adChar, 25 .Open End With 'This is getting the last used row in column A lastRow = ws.Cells(ws.Rows.count, "A").End(xlUp).Row 'Loop through the rows lRow = 1 Do While lRow <= lastRow 'Check if this is already data that we are counting rs.Filter = "" rs.Filter = "Value='" & ws.Range("A" & lRow).Value & "'" If rs.RecordCount = 0 Then 'If this is a new value, add a new row for it rs.AddNew rs.Fields("Value").Value = ws.Range("A" & lRow).Value rs.Fields("Count").Value = 1 rs.Update End If lRow = lRow + 1 Loop 'Remove the filer and move to the first record in the rs rs.Filter = "" rs.MoveFirst 'Loop through the data we found and write it out Do While rs.EOF = False ts.WriteLine ws.Cells(rs.Fields("Value").Value) rs.MoveNext Loop 'Clean up ts.Close: Set ts = Nothing Set fs = Nothing End Sub 

这是一个使用Dictionary获取不同值的例子, Join()使结果文本和FileSystemObject将文本保存到一个文件:

 Sub WriteDistinctToFile() Dim rngSource As Range Dim varItem As Variant Dim arrDistinct() As Variant With ActiveWorkbook.Sheets("Sheet1") Set rngSource = Intersect(.UsedRange, .Columns(1)) ' only used cells in first column End With With CreateObject("Scripting.Dictionary") .Item("") = "" ' add empty key to remove it later For Each varItem In rngSource.Value .Item(varItem) = "" ' add each cell value to unique keys Next .Remove "" ' remove empty value arrDistinct = .Keys() ' convert to array End With With CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt", 2, True, 0) ' open text file for output in ASCII .Write Join(arrDistinct, vbCrLf) ' join values from array into new line separated string, then write to file .Close End With End Sub