Help and Support

Identificativo articolo: 260819 - Ultima modifica: lunedì 17 aprile 2006 - Revisione: 8.0

Il metodo InviaOggetto non viene eseguito in Access 2000

Questo articolo è stato precedentemente pubblicato con il codice di riferimento I260819
Utenti esperti: sono richieste conoscenze avanzate di gestione di codice, interoperabilità e funzioni multiutente.

Le informazioni contenute in questo articolo si applicano ai database di Microsoft Access (mdb) e ai progetti di Microsoft Access (adp).

In questa pagina

Espandi tutto | Chiudi tutto

Sintomi

Quando si utilizza il metodo InviaOggetto in Microsoft Access 2000 per inviare un messaggio di posta elettronica, è possibile che si verifichi uno dei seguenti problemi:
  • Il metodo InviaOggetto non viene completato senza alcuna indicazione. Il messaggio non viene inviato ma non vengono visualizzati errori o avvisi che il messaggio di posta elettronica non è stato inviato.
  • È possibile che venga visualizzato un messaggio di errore analogo al seguente:
    Questo programma ha eseguito una operazione non valida e sarà terminato.

    Se il problema persiste, contattare il fornitore del programma.
    Quando si fa clic su Dettagli (in Microsoft Windows Millennium Edition premere ALT+D), viene visualizzato il messaggio seguente:
    MSACCESS.EXE ha provocato un errore di pagina non valida nel modulo KERNEL32.DLL in 0137:bff78040.
    NOTA: l'indirizzo di memoria effettivo può variare.
  • È possibile che venga visualizzato un messaggio di errore analogo al seguente:
    Errore di runtime '2501':

    L'azione InviaOggetto è stata annullata.
  • È possibile che venga visualizzato un messaggio di errore analogo al seguente:

    Errore di runtime 2487 "L'argomento tipo di oggetto per l'azione o il metodo è vuoto o non valido"
  • Viene visualizzato un messaggio di errore analogo al seguente:

    Errore di runtime 2958 "Errore riservato"

Cause

Questo problema può verificarsi in presenza di una delle seguenti condizioni:
  • Il messaggio contiene un numero eccessivo di caratteri. Questo comportamento è stato documentato con messaggi contenenti da 70 a 2268 caratteri.

    Nota Questo numero può essere superiore o inferiore a seconda del computer.
  • Il metodo InviaOggetto viene eseguito più di una volta nella stessa routine.

Risoluzione

Per risolvere il problema, procurarsi l'ultimo service pack per Microsoft Office 2000. Per ulteriori informazioni su come ottenere il service pack più recente per Microsoft Office 2000, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
276367  (http://support.microsoft.com/kb/276367/ ) Come ottenere la versione più recente del Service Pack di Office 2000
Importante Non installare Microsoft Office 2000 Service Pack 3 (SP-3) se prima non è stato installato Microsoft Office 2000 Service Release 1/1a (SR-1/SR-1a). Per ulteriori informazioni su come ottenere Office 2000 Service Release 1/1a (SR1/SR1a), fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
245025  (http://support.microsoft.com/kb/245025/ ) Reperimento e installazione di Microsoft Office 2000 SR-1/SR-1a

Workaround

Per risolvere questo problema, adottare una delle seguenti risoluzioni:
  • Ridurre la lunghezza del messaggio.

    Nota Questa risoluzione funziona solo per la prima condizione descritta nella sezione "Cause". Le altre risoluzioni sono valide per entrambe le condizioni descritte nella sezione "Cause".
  • Se è necessario inviare un messaggio senza allegare oggetti di Access, eseguire l'operazione in modo automatico tramite le librerie di oggetti di Outlook o CDO (Collaborative Data Objects).

    Nota Se Microsoft Outlook è stato installato in modalità Solo posta Internet (IMO), non è possibile utilizzare CDO e MAPI. Per ulteriori informazioni, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
    252720  (http://support.microsoft.com/kb/252720/ ) INFO: MAPI e CDO non supportati in Outlook in modalità Solo posta Internet
    Per ulteriori informazioni sull'invio di un messaggio utilizzando la libreria di oggetti di Microsoft Outlook, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
    161088  (http://support.microsoft.com/kb/161088/ ) Utilizzo dell'automazione per inviare un messaggio di Microsoft Outlook
  • Quando è necessario allegare oggetti di Access a un messaggio, per risolvere il problema utilizzare la seguente routine di Microsoft Visual Basic, Applications Edition (VBA) di esempio.

    Procedura di esempio

    Microsoft fornisce esempi di programmazione a scopo puramente illustrativo, senza alcuna garanzia di qualsiasi tipo, sia espressa che implicita, ivi incluse, senza limitazioni, le garanzie implicite di commerciabilità o idoneità per uno scopo particolare. In questo articolo si presuppone che l'utente conosca il linguaggio di programmazione in questione e gli strumenti utilizzati per creare ed eseguire il debug delle procedure. Gli esperti Microsoft sono autorizzati a fornire spiegazioni in merito alla funzionalità di una particolare procedura, ma in nessun caso a modificare questi esempi per fornire funzionalità aggiuntive o a creare procedure atte a soddisfare specifiche esigenze. Il codice seguente potrebbe non funzionare se nel computer è stato installato l'aggiornamento di protezione per la posta elettronica di Outlook. Per ulteriori informazioni su questo aggiornamento per Outlook 2000, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
    262631  (http://support.microsoft.com/kb/262631/ ) Informazioni sull'aggiornamento per la protezione della posta elettronica di Outlook
    Per ulteriori informazioni su questo aggiornamento per Outlook 98, fare clic sul numero dell'articolo della Microsoft Knowledge Base riportato di seguito:
    262617  (http://support.microsoft.com/kb/262617/ ) Informazioni sull'aggiornamento per la protezione della posta elettronica di Outlook
    1. Avviare Access 2000.
    2. Aprire il database di esempio Northwind.mdb.
    3. Scegliere Modulo di classe dal menu Inserisci.

      Verrà aperto un nuovo modulo di classe vuoto nell'ambiente Visual Basic.
    4. Scegliere Riferimenti dal menu Strumenti.
    5. Nella finestra di dialogo Riferimenti, selezionare la casella di controllo relativa alla libreria di Microsoft CDO 1.21. Se questa libreria di oggetti non è elencata nella finestra di dialogo Riferimenti, scegliere Sfoglia e cercare il file Cdo.dll.

      In un computer che esegue Microsoft Windows 95 o Microsoft Windows 98 questo file si trova in genere nella cartella C:\Programmi\File comuni\System\Mapi\1033\95.

      In un computer che esegue Microsoft Windows NT o Microsoft Windows 2000 questo file si trova in genere nella cartella C:\Programmi\File comuni\System\Mapi\1033\NT.

      Se il file Cdo.dll non viene trovato nel computer, riavviare il programma di installazione di Office 2000, scegliere Aggiungi/Rimouvi caratteristiche, quindi in Microsoft Outlook per Windows impostare l'esecuzione di CDO dal computer locale.
    6. Scegliere OK per chiudere la finestra di dialogo Riferimenti.
    7. Aggiungere il seguente codice al modulo di classe:
      Option Compare Database
      Option Explicit
      
      Private MAPISession As MAPI.Session
      Private MAPIMessage As Message
      Private MAPIRecipient As MAPI.Recipient
      Private MAPIAttachment As MAPI.Attachment
      Private reciparray
      Private strFileName As String
      
      
      Private Type OSVERSIONINFO
          dwOSVersionInfoSize As Long
          dwMajorVersion As Long
          dwMinorVersion As Long
          dwBuildNumber As Long
          dwPlatformId As Long
          szCSDVersion As String * 128
      End Type
      
      Private Const REG_SZ As Long = 1
      Private Const REG_DWORD As Long = 4
      Private Const HKEY_CURRENT_USER = &H80000001
      Private Const ERROR_NONE = 0
      Private Const ERROR_BADDB = 1
      Private Const ERROR_BADKEY = 2
      Private Const ERROR_CANTOPEN = 3
      Private Const ERROR_CANTREAD = 4
      Private Const ERROR_CANTWRITE = 5
      Private Const ERROR_OUTOFMEMORY = 6
      Private Const ERROR_INVALID_PARAMETER = 7
      Private Const ERROR_ACCESS_DENIED = 8
      Private Const ERROR_INVALID_PARAMETERS = 87
      Private Const ERROR_NO_MORE_ITEMS = 259
      Private Const KEY_ALL_ACCESS = &H3F
      Private Const REG_OPTION_NON_VOLATILE = 0
      
      Private Declare Function GetVersionEx Lib "kernel32" _
         Alias "GetVersionExA" _
               (ByRef lpVersionInformation As OSVERSIONINFO) As Long
      
      
      Private Declare Function RegCloseKey Lib "advapi32.dll" _
               (ByVal hKey As Long) As Long
      
      Private Declare Function RegOpenKeyEx Lib "advapi32.dll" _
         Alias "RegOpenKeyExA" _
               (ByVal hKey As Long, _
               ByVal lpSubKey As String, _
               ByVal ulOptions As Long, _
               ByVal samDesired As Long, _
               phkResult As Long) As Long
      
      Private Declare Function RegQueryValueExString Lib "advapi32.dll" _
         Alias "RegQueryValueExA" _
               (ByVal hKey As Long, _
               ByVal lpValueName As String, _
               ByVal lpReserved As Long, _
               lpType As Long, _
               ByVal lpData As String, _
               lpcbData As Long) As Long
      
      Private Declare Function RegQueryValueExLong Lib "advapi32.dll" _
         Alias "RegQueryValueExA" _
               (ByVal hKey As Long, _
               ByVal lpValueName As String, _
               ByVal lpReserved As Long, _
               lpType As Long, lpData As Long, _
               lpcbData As Long) As Long
      
      Private Declare Function RegQueryValueExNULL Lib "advapi32.dll" _
         Alias "RegQueryValueExA" _
               (ByVal hKey As Long, _
               ByVal lpValueName As String, _
               ByVal lpReserved As Long, _
               lpType As Long, _
               ByVal lpData As Long, _
               lpcbData As Long) As Long
               
      Private Declare Function GetTempPath Lib "kernel32" _
               Alias "GetTempPathA" (ByVal nBufferLength As Long, _
               ByVal lpBuffer As String) As Long
      
      Public Enum accSendObjectOutputFormat
          accOutputRTF = 1
          accOutputTXT = 2
          accOutputSNP = 3
          accOutputXLS = 4
      End Enum
      
      Public Sub SendObject(Optional ObjectType As Access.AcSendObjectType = acSendNoObject, _
                            Optional ObjectName, _
                            Optional OutputFormat As accSendObjectOutputFormat, _
                            Optional EmailAddress, _
                            Optional CC, _
                            Optional BCC, _
                            Optional Subject, _
                            Optional MessageText, _
                            Optional EditMessage)
          
          
          Dim strTmpPath As String * 512
          Dim sTmpPath As String
          Dim strExtension As String
          Dim nRet As Long
      
          StartMessagingAndLogon
          Set MAPIMessage = MAPISession.Outbox.Messages.Add
          If ObjectType <> -1 Then
              If IsMissing(ObjectName) Or IsMissing(OutputFormat) Then
                  MsgBox "The object type, name, or output format is not valid. Cannot send message.", vbCritical
                  MAPISession.Outbox.Messages.Delete
                  GoTo accSendObject_Exit
              Else
                  strExtension = GetExtension(OutputFormat)
                  nRet = GetTempPath(512, strTmpPath)
                  If (nRet > 0 And nRet < 512) Then
                      If InStr(strTmpPath, Chr(0)) > 0 Then
                          
                          sTmpPath = RTrim(Left(strTmpPath, InStr(1, strTmpPath, Chr(0)) - 1))
                      End If
                      strFileName = sTmpPath & ObjectName & strExtension
                  End If
                  On Error Resume Next
                  DoCmd.OutputTo ObjectType, ObjectName, GetOutputFormat(OutputFormat), strFileName, False
                  
                  If Err.Number = 0 Then
                      Set MAPIAttachment = MAPIMessage.Attachments.Add
                      With MAPIAttachment
                          .Name = ObjectName
                          .Type = CdoFileData
                          .Source = strFileName
                      End With
                      Kill strFileName
                    
                  Else
                      MsgBox "The object type, name, or output format is not valid. Cannot send message.", vbCritical
                      MAPISession.Outbox.Messages.Delete
                      GoTo accSendObject_Exit
                  End If
              End If
          End If
          
          If Not IsMissing(EmailAddress) Then
              reciparray = Split(EmailAddress, ";", -1, vbTextCompare)
              ParseAddress CdoTo
              Erase reciparray
          End If
          If Not IsMissing(CC) Then
              reciparray = Split(CC, ";", -1, vbTextCompare)
              ParseAddress CdoCc
              Erase reciparray
          End If
          
          If Not IsMissing(BCC) Then
              reciparray = Split(BCC, ";")
              ParseAddress CdoBcc
              Erase reciparray
          End If
          
          If Not IsMissing(Subject) Then
              MAPIMessage.Subject = Subject
          End If
          
          If Not IsMissing(MessageText) Then
              MAPIMessage.Text = MessageText
          End If
          
          If IsMissing(EditMessage) Then EditMessage = True
          
          MAPIMessage.Update
          MAPIMessage.Send savecopy:=True, ShowDialog:=EditMessage
              
      accSendObject_Exit:
          'Log off the MAPI session.
          MAPISession.Logoff
          Set MAPIAttachment = Nothing
          Set MAPIRecipient = Nothing
          Set MAPIMessage = Nothing
          Set MAPISession = Nothing
          Exit Sub
      
      End Sub
      
      Private Sub ParseAddress(RecipientType As MAPI.CdoRecipientType)
          Dim i As Variant
          For Each i In reciparray
              Set MAPIRecipient = MAPIMessage.Recipients.Add
              With MAPIRecipient
                  .Name = i
                  .Type = RecipientType
                  .Resolve
              End With
              Set MAPIRecipient = Nothing
          Next
      End Sub
      
      Private Function GetExtension(ObjectType As Long) As String
          Select Case ObjectType
              Case 1 'RTF
                  GetExtension = ".RTF"
              Case 2 'TXT
                  GetExtension = ".TXT"
              Case 3 'SNP
                  GetExtension = ".SNP"
              Case 4 'XLS
                  GetExtension = ".XLS"
          End Select
      End Function
      
      Private Function GetOutputFormat(ObjectType As Long)
          Select Case ObjectType
              Case 1 'RTF
                  GetOutputFormat = Access.acFormatRTF
              Case 2 'TXT
                  GetOutputFormat = Access.acFormatTXT
              Case 3 'SNP
                  GetOutputFormat = Access.acFormatSNP
              Case 4 'XLS
                  GetOutputFormat = Access.acFormatXLS
          End Select
      End Function
      
      Private Sub StartMessagingAndLogon()
          Dim sKeyName As String
          Dim sValueName As String
          Dim sDefaultUserProfile As String
          Dim osinfo As OSVERSIONINFO
          Dim retvalue As Integer
          
          On Error GoTo ErrorHandler
          Set MAPISession = CreateObject("MAPI.Session")
          
          'Try to log on.  If this fails, the most likely reason is
          'that you do not have an open session.  The error
          '-2147221231  MAPI_E_LOGON_FAILED returns.  Trap
          'the error in the ErrorHandler.
          MAPISession.Logon ShowDialog:=False, NewSession:=False
          Exit Sub
      
      ErrorHandler:
          Select Case Err.Number
             Case -2147221231  'MAPI_E_LOGON_FAILED
                'Need to determine what operating system is in use. The keys are different
                'for WinNT and Win95.
                osinfo.dwOSVersionInfoSize = 148
                osinfo.szCSDVersion = Space$(128)
                retvalue = GetVersionEx(osinfo)
                Select Case osinfo.dwPlatformId
                   Case 0   'Unidentified
                      MsgBox "Unidentified Operating System.  " & _
                         "Cannot log on to messaging."
                      Exit Sub
                   Case 1   'Win95
                      sKeyName = "Software\Microsoft\" & _
                                 "Windows Messaging " & _
                                 "Subsystem\Profiles"
          
                   Case 2   'NT
                       sKeyName = "Software\Microsoft\Windows NT\" & _
                                  "CurrentVersion\" & _
                                  "Windows Messaging Subsystem\Profiles"
                End Select
          
                sValueName = "DefaultProfile"
                sDefaultUserProfile = QueryValue(sKeyName, sValueName)
                MAPISession.Logon ProfileName:=sDefaultUserProfile, _
                                 ShowDialog:=False
                Exit Sub
             Case Else
                MsgBox "An error has occured while trying" & Chr(10) & _
                "to create and to log on to a new ActiveMessage session." & _
                Chr(10) & "Report the following error to your " & _
                "System Administrator." & Chr(10) & Chr(10) & _
                "Error Location: frmMain.StartMessagingAndLogon" & _
                Chr(10) & "Error Number: " & Err.Number & Chr(10) & _
                "Description: " & Err.Description
          End Select
      End Sub
      
      Private Function QueryValue _
          (sKeyName As String, _
          sValueName As String)
          
          Dim lRetVal As Long     'Result of the API functions.
          Dim hKey As Long        'Handle of the opened key.
          Dim vValue As Variant   'Setting of the queried value.
          
          lRetVal = RegOpenKeyEx(HKEY_CURRENT_USER, _
                      sKeyName, _
                      0, _
                      KEY_ALL_ACCESS, _
                      hKey)
          
          lRetVal = QueryValueEx(hKey, _
                      sValueName, _
                      vValue)
          QueryValue = vValue
          RegCloseKey (hKey)
          
      End Function
      
      Private Function QueryValueEx _
             (ByVal lhKey As Long, _
             ByVal szValueName As String, _
             vValue As Variant) As Long
          
          Dim cch As Long
          Dim lrc As Long
          Dim lType As Long
          Dim lValue As Long
          Dim sValue As String
          
          On Error GoTo QueryValueExError
          
          ' Determine the size and the type of the data to be read.
          lrc = RegQueryValueExNULL(lhKey, szValueName, 0&, lType, 0&, cch)
          If lrc <> ERROR_NONE Then Error 5
          
          Select Case lType
             ' For strings
             Case REG_SZ:
                sValue = String(cch, 0)
                lrc = RegQueryValueExString(lhKey, szValueName, 0&, lType, _
                   sValue, cch)
                If lrc = ERROR_NONE Then
                   vValue = Left$(sValue, cch)
                Else
                   vValue = Empty
                End If
             ' For DWORDS
             Case REG_DWORD:
                lrc = RegQueryValueExLong(lhKey, szValueName, 0&, lType, _
                   lValue, cch)
                If lrc = ERROR_NONE Then vValue = lValue
             Case Else
                'All other data types that are not supported.
                lrc = -1
          End Select
          
      QueryValueExExit:
          QueryValueEx = lrc
          Exit Function
      QueryValueExError:
          Resume QueryValueExExit
          End Function
       
      								
    8. Scegliere Finestra Proprietà dal menu Visualizza.
    9. Impostare la proprietà Name su accSendObject.
    10. Scegliere Modulo dal menu Inserisci.

      Verrà aggiunto un nuovo modulo standard al progetto VBA.
    11. Aggiungere al modulo il seguente codice:
          Sub SendMail()
             Dim clsSendObject As accSendObject
             Dim strMsg As String      
      
             Set clsSendObject = New accSendObject
             strMsg = String(3000, "a")
             clsSendObject.SendObject acSendReport, "Alphabetical list of products", accOutputSNP, _
               "<SomeEmailName>", , , "This is a test subject", strMsg, True
             Set clsSendObject = Nothing
          End Sub
       
      								
      Nel codice sostituire <SomeEmailName> con un indirizzo di posta elettronica valido.
    12. Dal menu Debug, scegliere Compila Nome progetto.
    13. Dal menu File, scegliere Salva Nome progetto.
    14. Per verificare questa routine, digitare la seguente riga nel riquadro della finestra immediata, quindi premere INVIO:
      SendMail
      								
      Con questo codice verrà inviato un messaggio di posta elettronica con allegato il report "Elenco alfabetico dei prodotti" come file snapshot.
    Uso e limitazioni

    Questo codice di esempio è stato creato per funzionare nel modo più simile possibile al metodo DoCmd.InviaOggetto di Access. La sintassi per richiamare questo metodo è simile a quella utilizzata per richiamare il metodo InviaOggetto in Access. Il metodo DoCmd.InviaOggetto presenta una limitazione dovuta al fatto che è stato creato per generare oggetti solo in formato testo (txt), Rich Text Format (rtf), Excel (xls) o snapshot (snp). Se si tenta di generare oggetti in altri formati, verrà restituito un errore.

    Nota Questo codice è stato verificato solo utilizzando Microsoft Outlook come client MAPI. È possibile che con altre applicazioni di posta compatibili MAPI non funzioni. Microsoft non supporta l'utilizzo di questo codice di esempio con applicazioni MAPI di altri produttori.

Status

Microsoft ha confermato che questo problema riguarda Access 2000.

Informazioni

Procedura per riprodurre il problema

  1. Avviare Access 2000.
  2. Aprire il database di esempio Northwind.mdb.
  3. Creare un nuovo modulo e digitare la seguente riga nella sezione Dichiarazioni se non è già presente:
       Option Explicit
     
    						
  4. Digitare la seguente routine:
     
    Sub SendObjectTest()
        Dim strMsg As String
        'Set the string variable to hold 3000 of the letter a.
        strMsg = String(3000, "a")
        DoCmd.SendObject acSendNoObject, , , "<SomeEmailName>", , , "Message Subject", strMsg, False
    End Sub
    						
    Nel codice sostituire <SomeEmailName> con un nome di posta elettronica valido.
  5. Per verificare questa routine, digitare la riga seguente nella finestra Immediata, quindi premere INVIO:
    SendObjectTest
    						
    È possibile che venga visualizzato uno dei sintomi indicati nella sezione "Sintomi".

Le informazioni in questo articolo si applicano a
  • Microsoft Access 2000 Standard Edition
Chiavi: 
kbqfe kbhotfixserver kbemail kbcode kbsample kbvba kbinfo kbprogramming kbbug KB260819
LE INFORMAZIONI CONTENUTE NELLA MICROSOFT KNOWLEDGE BASE SONO FORNITE SENZA GARANZIA DI ALCUN TIPO, IMPLICITA OD ESPLICITA, COMPRESA QUELLA RIGUARDO ALLA COMMERCIALIZZAZIONE E/O COMPATIBILITA' IN IMPIEGHI PARTICOLARI. L'UTENTE SI ASSUME L'INTERA RESPONSABILITA' PER L'UTILIZZO DI QUESTE INFORMAZIONI. IN NESSUN CASO MICROSOFT CORPORATION E I SUOI FORNITORI SI RENDONO RESPONSABILI PER DANNI DIRETTI, INDIRETTI O ACCIDENTALI CHE POSSANO PROVOCARE PERDITA DI DENARO O DI DATI, ANCHE SE MICROSOFT O I SUOI FORNITORI FOSSERO STATI AVVISATI. IL DOCUMENTO PUO' ESSERE COPIATO E DISTRIBUITO ALLE SEGUENTI CONDIZIONI: 1) IL TESTO DEVE ESSERE COPIATO INTEGRALMENTE E TUTTE LE PAGINE DEVONO ESSERE INCLUSE. 2) I PROGRAMMI SE PRESENTI, DEVONO ESSERE COPIATI SENZA MODIFICHE, 3) IL DOCUMENTO DEVE ESSERE DISTRIBUITO INTERAMENTE IN OGNI SUA PARTE. 4) IL DOCUMENTO NON PUO' ESSERE DISTRIBUITO A SCOPO DI LUCRO.

Traduzione articoli

 

Related Support Centers