Hi DoctorNadir,
With your workbook, you don't appear to define which worksheet to obtain the 'numero' value from and, moreover, you rely on the ActiveCell being the correct one. Consequently, you could be getting the value from the wrong cell in the wrong sheet! You need a better way of defining the numero value, such as:
Code:
With Workbooks(archivio)
numero = .Worksheets("Worksheetname").Cells(.Rows.Count, 1).End(xlUp).Row - 1
.Close SaveChanges:=True
End With
With this, you're actually retrieving the row number of the last-used row in column A (you could change the '1' in Cells(.Rows.Count, 1) for a different column). The '- 1' deducts the header row from the count, to get the record #.
Alternatively you could have the code point to a particular cell, irrespective of whether that cell is active:
numero = .Worksheets("Worksheetname").Range("A1").Value
but you should then test whether the source cell has a valid value (eg not blank or text and not out-of-bounds).
Also, unless the document has been disconnected from the datasource, you shouldn't need the line:
wdocSource.MailMerge.MainDocumentType = wdFormLetters
If the document has been disconnected from the datasource, you need more code for the SQL statement, etc. I also can't see why you'd need the line:
.NormalTemplate.Saved = True
since you're not apparently modifying the Normal template.
Aside from the above, there's no apparent errors in the code, though I'd be more inclined to use:
Code:
Private Sub cmdRegistraVerbale_Click()
'......................................
Workbooks.Open Filename:=archivio
'......................................
With Workbooks(archivio)
numero = .Worksheets("Worksheetname").Cells(.Rows.Count, 1).End(xlUp).Row - 1
.Close SaveChanges:=True
End With
'......................................
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then Set wd = CreateObject("Word.Application")
'......................................
On Error GoTo 0
With wd
Set wdocSource = .Documents.Open(modverbale)
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = numero
.LastRecord = numero
End With
.Execute Pause:=False
.DataSource.Close
.Close SaveChanges:=False
End With
.Visible = True
With .ActiveDocument
.SaveAs ("newfile.doc")
.PrintOut
.Close
End With
End With
End Sub