将所有单元格连续保存到.csv(或.txt)文件中[Excel2007]

时间:2013-06-17 09:57:00

标签: excel file io output

我在vba和excel的宏中完全是初学者,但我必须编写一个宏,它应该保存A行中的所有单元格,用逗号分隔,另外文本值应该用“”结束。 在.csv(.txt)文件的开头,我必须添加两行Name,Surname。

示例输出文件应如下所示: http://i.imgur.com/nq4fk6w.png

有人可以帮助我,或至少告诉我在哪里看。

RAY

编辑:

我做了类似下面的代码。它工作正常,但我仍然有两个问题:

  1. 如果我只检查公式值(例如= Ar2!C1),如何用引号关闭文本类型的单元格?
  2. 如何删除文件末尾出现的最后一个逗号?
  3. 输出文件屏幕:http://i.imgur.com/7OB9BOb.png?1

        Sub csvfile()
    
        Dim fs As Object, a As Object, i As Integer, s As String, t As String, l As String, mn As String
        Dim typ As String
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set a = fs.CreateTextFile("c:\tmp.txt", True)
            a.writeline ":DateRecipe"
            a.writeline ":Version,1"
            a.writeline ""
        For r = 1 To Range("A65536").End(xlUp).Row
            s = ""
            c = 1
            While Not IsEmpty(Cells(r, c))
                typ = cellType(Cells(r, c))
            If typ = "Text" Then
                s = s & Cells(r, c) & ","
                Else
                s = s & "331" & ","
                End If
                c = c + 1
            Wend
    
            a.writeline s 'write line
        Next r
    
    End Sub
    
    Function cellType(c)
        'Returns the cell type of the upper left
        'cell in a range
        Application.Volatile
        Set c = c.Range("A1")
        Select Case True
            Case IsEmpty(c): cellType = "Blank"
            Case Application.IsText(c): cellType = "Text"
            Case Application.IsLogical(c): cellType = "Logical"
            Case Application.IsErr(c): cellType = "Error"
            Case IsDate(c): cellType = "Date"
            Case InStr(1, c.Text, ":") <> 0: cellType = "Time"
            Case IsNumeric(c): cellType = "Value"
        End Select
    End Function
    

0 个答案:

没有答案