Failure to generate TXT file by routine for printing in VBA/Excel

Asked

Viewed 702 times

0

The form below refers to the code under VBA (Excel) presented below.

Formulário do VBA/Excel com dois botões para impressão em arquivo

This code refers to the printing of a spreadsheet on Excel by name "Imprint", as shown in the figure below. By the parameters passed on each button, will be printed all the data that appear in this worksheet, ie, is not the printing of a certain "range of cells".

Aba da planilha em Excel a ser impressa em arquivo

In the form of VBA the two buttons are named after:

CommandButtonImprimeEmPDF

CommandButtonImprimeEmTXT

And in the code there’s the routine ImprimeOuSalvaEmArquivo intended for printing or saving (generic form), in which case printing on archives shall be tested.

It is verified in the code that for the same "Path" and "filename" informed, as the event "click" of each button, the extension changes in the parameters passed to the printing routine, from PDF for TXT respectively.

When you press each button, the messages below are displayed indicating the location, name and extension of the generated files.

Mensagem do sucesso da impressão do segundo arquivo

Mensagem do sucesso da impressão do primeiro arquivo

The figure below shows the result in briefcase, where the files were generated correctly as to the place, name and extent.

Pasta com os arquivos salvos

When opening the file in PDF it is as predicted, but the file in TXT no, that is to say, it does not display the sheet text as expected (in text format).

The code goes below:

    Option Explicit

    Private Sub CommandButtonImprimeEmPDF_Click()

     'Salva impressão como arquivo em PDF
     ImprimeOuSalvaEmArquivo "Impressão", _
                             "", _
                             True, _
                             "F:\Teste\TesteDeImpressao1.PDF", _
                             False, _
                             "", _
                             1, _
                             True

     'Veja o significado das opções na rotina de impressão e salvamento

     End Sub


     Private Sub CommandButtonImprimeEmTXT_Click()

      'Salva impressão como arquivo em TXT
      ImprimeOuSalvaEmArquivo "Impressão", _
                              "", _
                              True, _
                              "F:\Teste\TesteDeImpressao1.TXT", _
                              False, _
                              "", _
                              1, _
                              True

     'Veja o significado das opções na rotina de impressão e salvamento

    End Sub


    Private Sub ImprimeOuSalvaEmArquivo( _
                ByVal NomeDaPlanilha As String, _
       Optional ByVal FaixaParaImprimir As String = "", _
       Optional ByVal ImprimirEmArquivo As Boolean = False, _
       Optional ByVal CaminhoNomeExtensaoDoArquivo As String = "", _
       Optional ByVal SelecionarImpressora As Boolean = False, _
       Optional ByVal NomeInternoDaImpressora As String = "", _
       Optional ByVal NumeroDeCopias As String = 1, _
       Optional ByVal MensagemAoFinalDaImpressao = False)

     Dim Planilha As Object

     'O objeto Planilha assume a planilha selecionada
     Set Planilha = Sheets(NomeDaPlanilha) 'Planilha anteriormente selecionada

     'Ativa a planilha a salvar/imprimir
     Planilha.Activate

     'Se optou por selecionar a impressora
     'e não solicitou salvar em arquivo
     If SelecionarImpressora _
        And Not ImprimirEmArquivo Then

         Application.Dialogs(xlDialogPrinterSetup).Show

     End If

     'Se o nome da impressora não foi informado anteriormente
     If NomeInternoDaImpressora = "" Then

         'Pega o nome da impressora ativa
         NomeInternoDaImpressora = ActivePrinter

     End If

     'Faixa a imprimir ou toda a planilha se vier com ""
     Planilha.PageSetup.PrintArea = FaixaParaImprimir

     'Imprime ou salva em arquivo
     ActiveWindow.SelectedSheets.PrintOut _
         Copies:=NumeroDeCopias, _
         ActivePrinter:=NomeInternoDaImpressora, _
         PrintToFile:=ImprimirEmArquivo, _
         PrToFileName:=CaminhoNomeExtensaoDoArquivo

     Beep

     'Se solicitou mensagem de local e nome do arquivo salvo/impresso
     If MensagemAoFinalDaImpressao Then

         MsgBox "Local e Nome do Arquivo Salvo/Impresso: " _
                & Chr(13) & Chr(13) & _
                CaminhoNomeExtensaoDoArquivo

     End If

 End Sub  

I tested by changing the internal names of printers that I have, they differ from the names present in the list below, it was necessary to take these names by means of code by VBA after selecting the printer and using a Msgbox, for example. According to the figure below, files were generated TXT in various formats, but not in the desired format (I did not present these tests here, as they were one for each printer in the list).

Impressoras disponíveis

A remark: if the print option in file is passed in the respective parameter, the dialog box for selecting the printer is not shown even if this has been requested by its parameter. If you want to test print for files using printer selection this part of the code needs to be adapted.

I know there are other ways to generate files TXT, for example, by means of macro, but I would like to use the routine that I have presented as it presents several possibilities to treat printing, such as the inclusion of titles and modification of margins (here the routine is simplified).

In reference to the instruction used (ActiveWindow.SelectedSheets.PrintOut) nay found how to properly generate the file TXT not even if it is possible through her.

I wonder if missed to indicate something in this statement or if she doesn’t do what I intend, generate files TXT in order to display the same layout as the spreadsheet data.

1 answer

0


I found the solution, I thought generate a printer that only prints in a text file, I searched and found this link:

http://faq.altoqi.com.br/content/365/862/pt-br/configurando-uma-impressora-generica_somente-texto.html

Despite being an example in previous version of Windows, I followed the steps and adapted to my case as I present the sequence that follows below.

  1. Add a printer:

inserir a descrição da imagem aqui

  1. Printer Local

inserir a descrição da imagem aqui

  1. Door LPT1

inserir a descrição da imagem aqui

  1. Manufacturer "Generic" and Printer "Generic / Text Only"

inserir a descrição da imagem aqui

  1. Printer Name. I left the pattern "Generic / Text Only":

inserir a descrição da imagem aqui

  1. Sharing, I chose not to share

inserir a descrição da imagem aqui

  1. Conclude (I unchecked the "set to default")

inserir a descrição da imagem aqui

The printer was generated below:

inserir a descrição da imagem aqui

I created a "Print" to make the new test, and adapted the printing parameters so that printer is requested before printing:

Private Sub CommandButtonImprimir_Click()

 ImprimeOuSalvaEmArquivo "Impressão", _
                         "", _
                         False, _
                         "F:\Teste\TesteDeImpressao2.TXT", _
                         True, _
                         "", _
                         1, _
                         True

End Sub

Note that I changed not only the file name, but activated the parameter "select printer".

Printer for text files appeared:

inserir a descrição da imagem aqui

And the result was this:

inserir a descrição da imagem aqui

The print went as desired, but I noticed a cactere at the end of the print. I will ask another question related to this, because I have no idea if you have to do not exit this character when generating the text file. The link to this new issue is:

/questions/137191/caractere-surge-no-final-ao-gerar-impress%C3%A3o-em-file-text-no-vba-excel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.