在 Excel 中导出具有逗号和引号分隔符的文本文件的过程

摘要

Microsoft Excel 没有用于将数据自动导出到文本文件的菜单命令,以便使用引号和逗号作为分隔符导出文本文件。 例如,没有用于自动创建包含以下数据的文本文件的命令:

“Text1”,“Text2”,“Text3”

但是,可以使用 Microsoft Visual Basic for Applications 过程在 Excel 中创建此功能。

更多信息

Microsoft 提供的编程示例仅用于进行说明,而不提供明示或默示担保。 这包括但不限于适销性或对特定用途的适用性的默示担保。 本文假设您熟悉正在演示的编程语言和用于创建和调试过程的工具。 Microsoft 支持工程师可以帮助解释特定过程的功能,但他们不会修改这些示例以提供新增功能或构建步骤以满足你的特定需要。

可以在类似于以下内容的 Visual Basic 过程中使用 Print # 语句,将同时包含引号和逗号的文本文件导出为分隔符。 若要使过程正常运行,请在运行数据之前选择包含数据的单元格。

在使用以下示例代码之前,请按照以下步骤操作:

  1. 打开新工作簿。

  2. 在 Microsoft Office Excel 2003 或 Microsoft Excel 2002 中,指向“工具”菜单上的“宏”,然后单击“Visual Basic 编辑器”。 或者,按 Alt+F11。

    在 Microsoft Office Excel 2007 中,单击“开发人员”选项卡,然后单击“代码”组中的“Visual Basic”。 或者,按 Alt + F11。

    注意

    若要在功能区中显示“开发人员”选项卡,请单击“Microsoft Office 按钮”,单击“Excel 选项”,单击“常用”类别,单击以选择“功能区检查”框中的“显示开发人员”选项卡,然后单击“确定”。

  3. 在 Visual Basic 编辑器中,单击“插入”菜单上的“模块”。

  4. 在模块表中键入或粘贴以下示例代码。

    Sub QuoteCommaExport()
       ' Dimension all variables.
       Dim DestFile As String
       Dim FileNum As Integer
       Dim ColumnCount As Long
       Dim RowCount As Long
    
       ' Prompt user for destination file name.
       DestFile = InputBox("Enter the destination filename" _
          & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
    
       ' Obtain next free file handle number.
       FileNum = FreeFile()
    
      ' Turn error checking off.
       On Error Resume Next
    
       ' Attempt to open destination file for output.
       Open DestFile For Output As #FileNum
    
       ' If an error occurs report it and end.
       If Err <> 0 Then
          MsgBox "Cannot open filename " & DestFile
          End
       End If
    
       ' Turn error checking on.
       On Error GoTo 0
    
       ' Loop for each row in selection.
       For RowCount = 1 To Selection.Rows.Count
    
       ' Loop for each column in selection.
          For ColumnCount = 1 To Selection.Columns.Count
    
            ' Write current cell's text to file with quotation marks.
             Print #FileNum, """" & Selection.Cells(RowCount, _
                ColumnCount).Text & """";
    
             ' Check if cell is in last column.
             If ColumnCount = Selection.Columns.Count Then
                ' If so, then write a blank line.
                Print #FileNum,
             Else
                ' Otherwise, write a comma.
                Print #FileNum, ",";
             End If
          ' Start next iteration of ColumnCount loop.
          Next ColumnCount
       ' Start next iteration of RowCount loop.
       Next RowCount
    
       ' Close destination file.
       Close #FileNum
    End Sub
    
  5. 在运行宏之前,选择要导出的数据,然后运行 QuoteCommaExport 子例程。