(EXCEL VBA)如何从txt输出中删除逗号和空格?

时间:2015-06-15 16:04:40

标签: excel vba excel-vba space comma

我有一个excel文件,如下所示:

3001 T81 90300010 001

3001 T81 90300011 001

问题是有些数字是存储为txt的数字。

还有字符串:" T81"

我需要输出的txt文件如下所示:

3001T8190300010001

没有空格,引用等。

我能够运行这个脚本来完成大部分的工作:

Dim myFile As String, rng As Range, cellValue As Variant, I As Integer, j As Integer

myFile = Application.DefaultFilePath & "\test_data_output.txt"
Set rng = Selection

Open myFile For Output As #1

For I = 1 To rng.Rows.Count
    For j = 1 To rng.Columns.Count

cellValue = rng.Cells(I, j).Value

If j = rng.Columns.Count Then
    Write #1, cellValue
Else
    Write #1, cellValue,
End If

    Next j
Next I

Close #1

现在它的输出并不完美:

3001" T81",90300010," 001"

3001" T81"" 90300011"" 001"

2 个答案:

答案 0 :(得分:1)

在您设置cellValue的行中,只需将字符串添加到一起(将值转换为字符串):

cellValue = cellValue + Cstr(rng.Cells(I, j).Value)

然后在你的下一个j和下一个之间我重置cellValue:

    Next j
    cellValue = ""
Next I

答案 1 :(得分:1)

Dim v as Variant

v = rng.Value

For i = LBound(v,1) to UBound(v,1)
    Write #1, Replace(Replace(Join(WorksheetFunction.Index(v,i,0),""),",","")," ","")
Next