我正在尝试将excel中的几列数据(其中包含空白单元格)导出到一个没有空格的单个数据到.txt文件中。 到目前为止,我已经汇编了一些代码,我可以成功导出一列。 我希望做的是复制/粘贴之前的一列,依此类推到.txt而不留空格。
Private Sub CommandButton2_Click()
Dim r As Range, c As Range, rng As Range
Dim sTemp As String
Dim UnusedColumn As Range
Dim Filename As String
Filename = ActiveWorkbook.Path & "\xxx.txt"
Open Filename For Output As #1
Set rng = Range("A2:A1000")
'Find a column with nothing in it
Set UnusedColumn = Cells.Find("*", , xlFormulas, , xlByColumns, xlPrevious).EntireColumn.Offset(0, 15)
'Create temporary calculation column to determine which cells to select (marked by an X)
Intersect(rng.EntireRow, UnusedColumn) = Evaluate("IF(" & rng.Address & "="""","""",""X"")")
'Make Selection
Intersect(UnusedColumn.SpecialCells(xlConstants).EntireRow, rng.EntireColumn).Select
'Remove Temporary Blank Caluclations
UnusedColumn.Clear
For Each r In Selection
sTemp = ""
For Each c In r.Cells
sTemp = sTemp & c.Text & Chr(9)
Next c
'Get rid of trailing tabs
While Right(sTemp, 1) = Chr(9)
sTemp = Left(sTemp, Len(sTemp) - 1)
Wend
Print #1, sTemp
Next r
Close #1
End Sub
其中有一些说明可以自动选择非空白单元格并导出每行没有引号。
以下是.txt与原始代码(一列)的外观: http://i.stack.imgur.com/DiB33.jpg
以下是列的外观: http://i.stack.imgur.com/9Tn3m.jpg
对于未经修饰的英语和代码,我们深表歉意。 提前谢谢!
答案 0 :(得分:0)
使用For Each Loop
迭代数组时,VBA按列迭代每个元素(第1列中的所有元素,然后是第2列中的所有元素......等等。)
用2.38秒写入10,000行x 255列,其中%50填充了14个数字存储为文本
Sub WriteToValues()
Dim Start: Start = Timer
Dim Data, v
Dim FileName As String
FileName = ActiveWorkbook.Path & "\xxx.txt"
Data = ActiveSheet.UsedRange.Value2
Open FileName For Output As #1
For Each v In Data
If v <> vbNullString Then Print #1, CStr(v)
Next
Close #1
Debug.Print Timer - Start
End Sub