在VBA中创建一个空白的csv文件

时间:2016-12-15 08:44:43

标签: excel vba csv vbscript

遇到一个小问题。我在不同的电子表格中运行来自VBScript的10个宏。哪个效果很好,但遇到了一个简单的问题。其中一个宏我需要将一些值导出到当前目录中的新CSV / txt文件中。

当我在VBA中尝试FileSystemObject时,它失败了。 (我认为因为我已经从VBScript运行宏)。所以我搜索了如何创建CSV或txt文件。每个答案都说SaveAs。这不是我需要的。我需要创建一个全新的CSV / txt文件并在以后填充它。但我找不到Create_CVS_File选项,该选项不是SaveAs

我的代码(见下文)失败了:Set csvFile = objFSO.CreateTextFile("unknown_models.csv")

Dim ClientCodeSelection As Range
Path = ActiveWorkbook.Path & "\"
file = Dir(Path)
csv_exist = 0

For Each c In Intersect(ActiveSheet.UsedRange.Offset(1, 0).Resize(numRows - 1, numColumns), Range(Columns(Rng1.Column), Columns(Rng1.Column)))
    'first check for correct event type, i.e not 'none franchised.'
    If Not LCase(c.Value) Like LCase("*non *") Then
        If InStr(sn1_joined, LCase(Cells(c.Row, rng2.Column))) > 0 Then
            'all good, not missing move on.
        Else
            'record value into csv or text file, called unknown_model.csv
            'first check to see if the file exists in the current directory
            While (file <> "")
                If InStr(file, "unknown_models.csv") Then
                   csv_exist = 1
                Else
                End If
                file = Dir
            Wend

            'if file didnt exist create it, otherwise add the data
            If csv_exist = 1 Then
                'just add data
            Else
                'create
                Set objFSO = CreateObject("Scripting.FileSystemObject")
                Set csvFile = objFSO.CreateTextFile("unknown_models.csv", True)
                'now add data
            End If

            Total = Total + 1
        End If
    End If
Next c
If Not ClientCodeSelection Is Nothing Then ClientCodeSelection.Select

得到了Vincent的出色帮助。最终代码:

Dim ClientCodeSelection As Range
Path = ActiveWorkbook.Path & "\"
ForAppending = 8

For Each c In Intersect(ActiveSheet.UsedRange.Offset(1, 0).Resize(numRows - 1, numColumns), Range(Columns(Rng1.Column), Columns(Rng1.Column)))
    'first check for correct event type, i.e not 'none franchised.'
    If Not LCase(c.Value) Like LCase("*non *") Then
        If InStr(sn1_joined, LCase(Cells(c.Row, rng2.Column))) > 0 Then
            'all good, not missing move on.
        Else
            'record value into csv or text file, called unknown_model.csv
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set openFile = objFSO.OpenTextFile(Path & "unknown_models.txt", ForAppending, True)
            openFile.Write Cells(c.Row, rng2.Column) & ","
            openFile.Close
            Total = Total + 1
        End If
    End If
Next c

If Not ClientCodeSelection Is Nothing Then ClientCodeSelection.Select

0 个答案:

没有答案