Monday, May 16, 2016

Excel: Procedure to export a text file with both comma and quote delimiters in Excel

Before you work with the following sample code, follow these steps:
  1. Open a new workbook.
  2. In Microsoft Office Excel 2003 or in Microsoft Excel 2002, point to Macro on the Tools menu, and then clickVisual Basic Editor. Alternatively, press ALT+F11.

    In Microsoft Office Excel 2007, click the Developer tab, and then click Visual Basic in the Code group. Alternatively, press ALT + F11.

    Note To show the Developer tab in the Ribbon, click the Microsoft Office Button, click Excel Options, click the Popular category, click to select the Show Developer tab in the Ribbon check box, and then clickOK.
  3. In the Visual Basic Editor, click Module on the Insert menu.
  4. Type or paste the following sample code in the module sheet.
    Sub QuoteCommaExport()
       ' Dimension all variables.
       Dim DestFile As String
       Dim FileNum As Integer
       Dim ColumnCount As Integer
       Dim RowCount As Integer
       ' 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 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,
                ' 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. Before you run the macro, select the data that you want to export, and then run the QuoteCommaExportsubroutine.

No comments:

Post a Comment