如何分离值与一个定义的字符VBA

我有VBA过程中写入数据到文本文件(.txt),但我需要分隔的值这个字符 – “|”。 你可以帮我吗?

Sub Sales_tmr() Dim myFile As String Dim rng As Range Dim cellValue As Variant Dim i As Integer Dim j As Integer myFile = Application.DefaultFilePath & "\sales.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, ' Here I will separeted char "|" End If Next j Next i Close #1 End Sub 

谢谢!

你可以尝试以下的对象? 也许, Open myFile For Output As #1有一些问题:

 Dim SpaceVar as String Dim Writer As Object SpaceVar = Chr(124) ' Basically your "|" Set Writer = CreateObject("ADODB.Stream") With Writer .Type = 2 ' Specifies stream type - save text data. .Charset = "utf-8" ' Specifies charset for the source text data. .lineseparator = 10 ' Pushes enter when a line is finished .Open End With ' Here you use the "Writer" Object as many times you want with the strings you want Writer.WriteText NameVar & SpaceVar & SurnameVar & SpaceVar & AgeVar ' These variables I didn't declare, but you should in case you wanted to use them to store your strings With Writer .SaveToFile FileNameString, 2 ' Saves (and overwrites) data ' be sure to declare the variable, should you use it! .Close End With Set Writer = Nothing 

不能把它添加到值?

 cellValue = rng.Cells(i, j).Value If j = rng.Columns.Count Then Write #1, cellValue Else cellValue = cellValue & "|" Write #1, cellValue, ' Here I will separeted char "|" End If 

更新

为了使其每行更新不带引号和逗号。 在你的第一个循环后移动你的写;

 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 cellValue = cellValue & "|" End If Next j Write #1, cellValue, Next i 

这将输出

“Joe |博客| 72”,“Dave | Mitchell | 34”,

等等

请参阅VB Write函数的文档: http : //msdn.microsoft.com/en-us/library/yxw69s8t%28v=vs.90%29.aspx

与Print函数不同的是,Write函数在写入文件时,会在string和引号之间插入逗号。

您将不得不使用不同的函数来将行写入文件,例如使用Scripting.FileSystemObjectWriteLine 。 请参阅http://msdn.microsoft.com/en-us/library/t5399c99%28v=vs.84%29.aspx