Jump to content
Fórum Script Brasil
  • 0

MALA DIRETA COM VBA


lauro leite
 Share

Question

Olá, Estou criando uma mala direta com VBA, a qual vincula um documento word. o problema é que quando clico no botão para gerar a carta (CommandButton1), é gerada sempre a carta do primeiro registro salvo na planilha (Plan2). eu gostaria que fosse gerado a carta com os dados que estão abertos no formulário, independente de qual linha esteja gravado.  Poderiam me ajudar? Tem como selecionar os dados do meu formulário aberto para gerar a carta ?Sou novato no VBA. Segue abaixo o código que estou usando:

Private Sub CommandButton1_Click()

 Dim wd As Object
    Dim wdocSource As Object
    Dim strWorkbookName As String

    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set wdocSource = wd.Documents.Open("C:\Users\LAU\Documents\MALA\Doc1")

    strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name

    wdocSource.MailMerge.MainDocumentType = wdFormLetters

    wdocSource.MailMerge.OpenDataSource _
            Name:=strWorkbookName, _
            AddToRecentFiles:=False, _
            Revert:=False, _
            Format:=wdOpenFormatAuto, _
            Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
            SQLStatement:="SELECT * FROM `Plan2$`"


    With wdocSource.MailMerge
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With

    wd.Visible = True
    wdocSource.Close SaveChanges:=False

    Set wdocSource = Nothing
    Set wd = Nothing

End Su

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Forum Statistics

    • Total Topics
      149.6k
    • Total Posts
      646.2k
×
×
  • Create New...