O texto formatado (.prn) é limitado a 240 caracteres por linha no Excel

Sintomas

No Microsoft Excel, quando você salva uma planilha como um arquivo Formatado texto (Delimitado por espaço) (.prn), todos os caracteres além do 200 caracteres fortieth são embrulhados para a próxima linha.

Observação

Se várias linhas na mesma folha contiverem texto além de 240 caracteres, o texto começará a ser encapsulado na linha após a última linha que contém texto.

Por exemplo, considere a seguinte planilha:

Célula Número de Caracteres
A1 40
A2 255
A3 10
A4 21
A5 2
A6 52
A7 255
A8 5
A9 3
A20 13

O arquivo de texto formatado resultante contém linhas com o seguinte número de caracteres:

Número de linha Caracteres
1 40
2 240
3 10
4 21
5 2
6 52
7 240
8 5
9 3
10-19 0
20 13
21 0
22 15
23-26 0
27 15

Após a última linha (neste exemplo, linha 20), a numeração de linha começa em 1 para as linhas que são encapsuladas. Na verdade, a linha 21 corresponde à linha 1, a linha 22 corresponde à linha 2 e assim por diante.

Motivo

Esse comportamento ocorre porque, por design, arquivos formatados de texto (delimitados por espaço) (.prn) têm um limite de 240 caracteres por linha.

Solução alternativa

A Microsoft oferece exemplos de programação somente para ilustração, sem garantias expressas ou implícitas. Isso inclui, mas não está limitado a, as garantias implícitas de qualidade comercial ou conformidade para uma determinada finalidade. Este artigo supõe que você conhece a linguagem de programação que está sendo demonstrada e as ferramentas usadas nos processos de criação e depuração. Os engenheiros de suporte da Microsoft podem ajudá-lo, fornecendo a explicação da funcionalidade de determinado procedimento, mas não modificarão estes exemplos para fornecer funcionalidade adicional nem criarão procedimentos específicos para atender às suas necessidades específicas. Para criar um arquivo de texto delimitado por espaço que exceda a limitação de 240 caracteres por linha, use uma macro semelhante à macro de exemplo a seguir.

Observação

Antes de executar essa macro, faça o seguinte:

  • Selecione as células a serem incluídas no arquivo de texto.
  • Verifique se as larguras de coluna são largas o suficiente para exibir a maior cadeia de caracteres em cada coluna. A largura máxima da coluna para uma única coluna do Excel é de 255 caracteres quando formatada com uma fonte de largura fixa.
  • Use os comandos de menu Style para formatar a planilha para usar uma fonte de largura fixa. Por exemplo, Courier é uma fonte de largura fixa.

O código de exemplo a seguir pode ser modificado para exportar dados delimitados com caracteres diferentes de um espaço. Você deve selecionar o intervalo de dados a serem exportados antes de executar essa macro de exemplo.

Sub ExportText()

Dim delimiter As String
   Dim quotes As Integer
   Dim Returned As String

       delimiter = " "

       quotes = MsgBox("Surround Cell Information with Quotes?", vbYesNo)

' Call the WriteFile function passing the delimiter and quotes options.
      Returned = WriteFile(delimiter, quotes)

' Print a message box indicating if the process was completed.
      Select Case Returned
         Case "Canceled"
            MsgBox "The export operation was canceled."
         Case "Exported"
            MsgBox "The information was exported."
      End Select

End Sub

'------------------------------------------------------------

Function WriteFile(delimiter As String, quotes As Integer) As String

  ' Dimension variables to be used in this function.
   Dim CurFile As String
   Dim SaveFileName
   Dim CellText As String
   Dim RowNum As Integer
   Dim ColNum As Integer
   Dim FNum As Integer
   Dim TotalRows As Double
   Dim TotalCols As Double

   ' Show Save As dialog box with the .TXT file name as the default.
   ' Test to see what kind of system this macro is being run on.
   If Left(Application.OperatingSystem, 3) = "Win" Then
      SaveFileName = Application.GetSaveAsFilename(CurFile, _
      "Text Delimited (*.txt), *.txt", , "Text Delimited Exporter")
   Else
       SaveFileName = Application.GetSaveAsFilename(CurFile, _
      "TEXT", , "Text Delimited Exporter")
   End If

   ' Check to see if Cancel was clicked.
      If SaveFileName = False Then
         WriteFile = "Canceled"
         Exit Function
      End If
   ' Obtain the next free file number.
      FNum = FreeFile()

   ' Open the selected file name for data output.
      Open SaveFileName For Output As #FNum

   ' Store the total number of rows and columns to variables.
      TotalRows = Selection.Rows.Count
      TotalCols = Selection.Columns.Count

   ' Loop through every cell, from left to right and top to bottom.
      For RowNum = 1 To TotalRows
         For ColNum = 1 To TotalCols
            With Selection.Cells(RowNum, ColNum)
            Dim ColWidth as Integer
            ColWidth=Application.RoundUp(.ColumnWidth, 0)
            ' Store the current cells contents to a variable.
            Select Case .HorizontalAlignment
               Case xlRight
                  CellText = Space(Abs(ColWidth - Len(.Text))) & .Text
               Case xlCenter
                  CellText = Space(Abs(ColWidth - Len(.Text))/2) & .Text & _
                             Space(Abs(ColWidth - Len(.Text))/2)
               Case Else
                  CellText = .Text & Space(Abs(ColWidth - Len(.Text)))
            End Select
            End With
   ' Write the contents to the file.
   ' With or without quotation marks around the cell information.
            Select Case quotes
               Case vbYes
                  CellText = Chr(34) & CellText & Chr(34) & delimiter
               Case vbNo
                  CellText = CellText & delimiter
            End Select
            Print #FNum, CellText;

   ' Update the status bar with the progress.
            Application.StatusBar = Format((((RowNum - 1) * TotalCols) _
               + ColNum) / (TotalRows * TotalCols), "0%") & " Completed."

   ' Loop to the next column.
         Next ColNum
   ' Add a linefeed character at the end of each row.
         If RowNum <> TotalRows Then Print #FNum, ""
   ' Loop to the next row.
      Next RowNum

   ' Close the .prn file.
      Close #FNum

   ' Reset the status bar.
      Application.StatusBar = False
      WriteFile = "Exported"
   End Function

Observação

O arquivo de saída que essa rotina cria é, por definição, diferente de um arquivo Text(*.prn) formatado. Por definição, o arquivo de texto formatado não pode conter mais de 240 caracteres por linha. Além disso, o arquivo de texto formatado também contém informações de fonte de impressora. Essa macro de exemplo não. Essa solução foi projetada para dar flexibilidade ao exportar para arquivos de texto.