Jump to content

@error & variable


Recommended Posts

Hi guys!

Trying to code everything better and have fail safes as at this point i havent really used any @errors... i just want to make sure im using this correctly... 

Is this the correct way to code that if it errors at all during the function then call the othe rfunction _inetsmtpmailcom which will send me an email using $mailfilepath1 in that function as the body.

I hope i have set up the @error right and also that $mailfilepath1 will pass the vale of $sp3 which is a global to the inetsmtpmailcom function as a local as i have many of these functions to run and just wan tto use the same inetsmtpmailcom function for all of the functions just passing the unique $mailfilepath1 function to it.

Hope this makes sense

func sp3
   $mailfilepath1 = $sp3
$oExcel = _Excel_Open(0,0,0,1,0)
_Excel_BookOpen($oExcel,$mainfilepath & $sp3,0,0)
$oExcel.Run("unprotect")
$oExcel.Run("refreshdb")
$oExcel.Run("protect")
_Excel_Close($oExcel)
If @error Then 
   call _inetsmtpmailcom()
endfunc
Link to comment
Share on other sites

You have no EndIf in your If statement, and you wrote the Call line wrong.

BTW, don't use Call unless absolutely necessary, which is just about never.

Also, @error will only read an error from the last function called before you read it, so if it errors somewhere between Func sp3() and the $oExcel.Run("protect") line you won't detect it with your @error check. That @error will read only the error condition returned by _Excel_Close.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

func sp3()
$mailfilepath1 = $sp3
$oExcel = _Excel_Open(0,0,0,1,0)
errorcheck()
_Excel_BookOpen($oExcel,$mainfilepath & $sp3,0,0)
errorcheck()
$oExcel.Run("unprotect")
errorcheck()
$oExcel.Run("refreshdb")
errorcheck()
$oExcel.Run("protect")
errorcheck()
_Excel_Close($oExcel)
errorcheck()
endfunc

func errorcheck()
If @error Then 
 _inetsmtpmailcom()
endif
endfunc

Like this?

Edited by 13lack13lade
Link to comment
Share on other sites

Close, pass @ERROR as a variable to the function like...

local $str = stringsplit('some string','|') ;   sets @ERROR to "1"
_ERR1(@ERROR)

func _ERR1($err)
    ConsoleWrite('ERROR Code Passing @ERROr as a variable = ' & $err & @CRLF)
endfunc

kylomas

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

i see!

That would mean that i would also have to pass the variable $mailfilepath1 to the _inetsmtpmailcom() function as well so it knows where its getting the value from?

Like this:

func sp3()
$mailfilepath1 = $sp3
$oExcel = _Excel_Open(0,0,0,1,0)
_Excel_BookOpen($oExcel,$mainfilepath & $sp3,0,0)
errorcheck(@error)
$oExcel.Run("unprotect")
errorcheck(@error)
$oExcel.Run("refreshdb")
errorcheck(@error)
$oExcel.Run("protect")
errorcheck(@error)
_Excel_Close($oExcel)
errorcheck(@error)
endfunc

func errorcheck()
If @error Then 
 _inetsmtpmailcom($mailfilepath1)
endif
endfunc
Edited by 13lack13lade
Link to comment
Share on other sites

I get the distinct feeling you're not testing your code. For example you're passing a value to the errorcheck function and yet you don't have function called errorcheck that accepts one parameter.

Couple of steps...

  1. Open the help file
  2. Read about functions
  3. Read about @error
  4. Re-read kylomas' post

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Re-Read the help file as suggested (did read the first time and looked at random error statements and i think i get it now)

Do i simply provide the func errorcheck($withanyvariablename) which then gets set to a value by the called errorcheck(@error) function which is then use to determine if it is <> 0 which determines if an error has occurred?

like such: - If so, the help file states @error returns to the value 0 at the end of each function, does this mean that it returns to 0 after each errorcheck call or at the end of func sp3?

func sp3()
$mailfilepath1 = $sp3
$oExcel = _Excel_Open(0,0,0,1,0)
_Excel_BookOpen($oExcel,$mainfilepath & $sp3,0,0)
errorcheck(@error)
$oExcel.Run("unprotect")
errorcheck(@error)
$oExcel.Run("refreshdb")
errorcheck(@error)
$oExcel.Run("protect")
errorcheck(@error)
_Excel_Close($oExcel)
errorcheck(@error)
endfunc

func errorcheck($variables)
If $variables <> 0 Then 
 _inetsmtpmailcom($mailfilepath1)
endif
endfunc

 i have read the help file that is the first place i went to and you are correct, in this instance i cannot test my code YET.. but i know that my @error was not correct so needed to solve this issue at some point regardless.. 

Edited by 13lack13lade
Link to comment
Share on other sites

13lack13lade,  

You want to test for errors in two places, from the Excel calls and from the mail routine.  Without seeing all of your code I am guessing that you need something like this... 

; variables for COM error handling
local $oMyRet[2]                                        ;   array for error message from mail routine
local $oMyError = ObjEvent("AutoIt.Error", "MyErrFunc") ;   error routine

Func sp3()
    $mailfilepath1 = $sp3
    $oExcel = _Excel_Open(0, 0, 0, 1, 0)
    if @error then _Err(@ERROR)
    _Excel_BookOpen($oExcel, $mainfilepath & $sp3, 0, 0)
    if @error then _Err(@ERROR)
    $oExcel.Run("unprotect")
    $oExcel.Run("refreshdb")
    $oExcel.Run("protect")
    _Excel_Close($oExcel)
    if @error then _Err(@ERROR)
EndFunc   ;==>sp3

; This handles @ERROR
func _Err($err)
    ;
    ; do some staging
    ;
    ConsoleWrite('Sending Excel Error Notification Email...')
    _inetsmtpmailcom($mailfilepath1)
    ; this tests for an error returned from the mail routine
    ConsoleWrite(@error ? @crlf & '! Error sending mail = ' & $oMyRet[1] & @crlf : 'Send complete' & @CRLF)
    ;
    ; Go back and do something, or exit the script
    ;
EndFunc

; This handles errors from COM routines.  For example, you might have syntax wrong for a method or property, object may not exist, etc.
Func MyErrFunc()
    $HexNumber = Hex($oMyError.number, 8)
    $oMyRet[0] = $HexNumber
    $oMyRet[1] = StringStripWS($oMyError.description, 3)
    SetError(1)
    Return
EndFunc   ;==>MyErrFunc

kylomas

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

It's quite annoying when people lack patience in testing when they have the opportunity to do so and instead rely on others to do it for them.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I could have also done it like such however wanted to do it in the 'correct' way as to not constantly repeat lines and so it is structured better. - Trying to learn, not get people to test things for me..

func sp3()
$mailfilepath1 = $sp3
$oExcel = _Excel_Open(0,0,0,1,0)
if @error then
_inetsmtpmailcom($mailfilepath1)
endif
_Excel_BookOpen($oExcel,$mainfilepath & $sp3,0,0)
if @error then
_inetsmtpmailcom($mailfilepath1)
endif
$oExcel.Run("unprotect")
$oExcel.Run("refreshdb")
$oExcel.Run("protect")
_Excel_Close($oExcel)
if @error then
_inetsmtpmailcom($mailfilepath1)
endif
endfunc
Edited by 13lack13lade
Link to comment
Share on other sites

Variable used without being declared.:
Global $body = $mailfilepath1
Global $body = ^ ERROR
 
now what have i done wrong? :(
 
Here is my total script, i am trying to create something like a UDF holding all these functions which i can then create another script with that UDF and just call the functions however i am having issues with the variables inside the functions and functions within functions i think? Yes my code is ugly, Yes i'm a noob but i am willing to learn.
 
My thought process was to change change the values of the variables $month depending on @mon and $mainfilepath depending on $month and $year. then keep those values and call a function for example _afr1 which uses $mainfilepath and $afr1 (filename) to give a filepath for excel to open that specific book, run the macros save and close. IF IT FAILS - run the email CDO at the bottom with $mailfilepath1 so that i can identify which file an error has occurred on.
 
 
 
#include <Date.au3>
#include <MsgBoxConstants.au3>
#include <Excel.au3>
#Include<file.au3>

;~~~~~~~~~~~~~~~~~~~~~~~~~~~~DECLARES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;date and time
Global $month = ""
Global $mainfilepath = ""
Global $year = @year-2000
Global $filemonthyear = $month & $year
;africa filenames
Global $afr1 = "01 Africa Supplier Summary " & $filemonthyear & ".xlsb"

;------------current month - SET VALUE TO $month by using current system date-----
if @mon = "01" then
   $month = "Jan"
Elseif @mon = "02" then
   $month = "Feb"
ElseIf @mon = "03" then
   $month = "Mar"
elseif @mon = "04" Then
   $month = "Apr"
elseif @mon = "05" Then
   $month = "May"
elseif @mon = "06" Then
   $month = "Jun"
elseif @mon = "07" Then
   $month = "Jul"
elseif @mon = "08" Then
   $month = "Aug"
elseif @mon = "09" Then
   $month = "Sep"
elseif @mon = "10" Then
   $month = "Oct"
elseif @mon = "11" Then
   $month = "Nov"
elseif @mon = "12" Then
   $month = "Dec"
EndIf
;filepaths ------ SET VALUE TO $mailfilepath as set by above and using system date.-------
If $filemonthyear = "Nov14" Then
$mainfilepath = "\\serverfilepath\1\"
elseIf   $filemonthyear = "Dec14" Then
$mainfilepath = "\\serverfilepath\2\"
elseIf   $filemonthyear = "Jan15" Then
$mainfilepath = "\\serverfilepath\3\"
elseIf   $filemonthyear = "Feb15" Then
$mainfilepath = "\\serverfilepath\4\"
elseIf   $filemonthyear = "Mar15" Then
$mainfilepath = "\\serverfilepath\5\"
elseIf   $filemonthyear = "Apr15" Then
$mainfilepath = "\\serverfilepath\6\"
elseIf   $filemonthyear = "May15" Then
$mainfilepath = "\\serverfilepath\7\"
elseIf $filemonthyear = "Jun15" Then
$mainfilepath = "\\serverfilepath\8\"

 EndIf
; ------------------------------------- functions -----------------------------------
func _afr1()
$mailfilepath1 = $afr1
$oExcel = _Excel_Open(0,0,0,1,0)
if @error then
_inetsmtpmailcom($mailfilepath1,$afr1)
endif
_Excel_BookOpen($oExcel,$mainfilepath & $afr1,0,0)
if @error then
_inetsmtpmailcom($mailfilepath1,$afr1)
endif
$oExcel.Run("unprotect")
$oExcel.Run("refreshdb")
$oExcel.Run("protect")
_Excel_Close($oExcel)
if @error then
_inetsmtpmailcom($mailfilepath1,$afr1)
endif
endfunc

;email section---------------------------------------------------------- 
Global $smtpserver = "smtp"
Global $fromname = "13lack13lade"
Global $fromaddress = "email_adress"
Global $toaddress = "email_adress"
Global $subject = "Reporting Fail"
Global $body = $mailfilepath1
Global $attachfiles = ""
Global $ccaddress = ""
Global $bccaddress = ""
Global $importance = "Normal"
Global $username = ""
Global $password = ""
Global $ipport = 25
Global $ssl = 0
Global $omyret[2]
Global $omyerror = ObjEvent("AutoIt.Error", "MyErrFunc")
$rc = _inetsmtpmailcom($smtpserver, $fromname, $fromaddress, $toaddress, $subject, $body, $attachfiles, $ccaddress, $bccaddress, $importance, $username, $password, $ipport, $ssl)
If @error Then
    MsgBox(0, "Error sending message", "Error code:" & @error & "  Description:" & $rc)
EndIf

Func _inetsmtpmailcom($s_smtpserver, $s_fromname, $s_fromaddress, $s_toaddress, $s_subject = "", $as_body = "", $s_attachfiles = "", $s_ccaddress = "", $s_bccaddress = "", $s_importance = "Normal", $s_username = "", $s_password = "", $ipport = 25, $ssl = 0)
    Local $objemail = ObjCreate("CDO.Message")
    $objemail.from = '"' & $s_fromname & '" <' & $s_fromaddress & ">"
    $objemail.to = $s_toaddress
    Local $i_error = 0
    Local $i_error_desciption = ""
    If $s_ccaddress <> "" Then $objemail.cc = $s_ccaddress
    If $s_bccaddress <> "" Then $objemail.bcc = $s_bccaddress
    $objemail.subject = $s_subject
    If StringInStr($as_body, "<") AND StringInStr($as_body, ">") Then
        $objemail.htmlbody = $as_body
    Else
        $objemail.textbody = $as_body & @CRLF
    EndIf
    If $s_attachfiles <> "" Then
        Local $s_files2attach = StringSplit($s_attachfiles, ";")
        For $x = 1 To $s_files2attach[0]
            $s_files2attach[$x] = _pathfull($s_files2attach[$x])
            ConsoleWrite("@@ Debug(62) : $S_Files2Attach = " & $s_files2attach & @LF & ">Error code: " & @error & @LF)
            If FileExists($s_files2attach[$x]) Then
                $objemail.addattachment($s_files2attach[$x])
            Else
                ConsoleWrite("!> File not found to attach: " & $s_files2attach[$x] & @LF)
                SetError(1)
                Return 0
            EndIf
        Next
    EndIf
    $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = $s_smtpserver
    If Number($ipport) = 0 Then $ipport = 25
    $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = $ipport
    If $s_username <> "" Then
        $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/sendusername") = $s_username
        $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = $s_password
    EndIf
    If $ssl Then
        $objemail.configuration.fields.item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    EndIf
    $objemail.configuration.fields.update
    Switch $s_importance
        Case "High"
            $objemail.fields.item("urn:schemas:mailheader:Importance") = "High"
        Case "Normal"
            $objemail.fields.item("urn:schemas:mailheader:Importance") = "Normal"
        Case "Low"
            $objemail.fields.item("urn:schemas:mailheader:Importance") = "Low"
    EndSwitch
    $objemail.fields.update
    $objemail.send
    If @error Then
        SetError(2)
        Return $omyret[1]
    EndIf
    $objemail = ""
EndFunc

Exit

Func myerrfunc()
    $hexnumber = Hex($omyerror.number, 8)
    $omyret[0] = $hexnumber
    $omyret[1] = StringStripWS($omyerror.description, 3)
    ConsoleWrite("### COM Error !  Number: " & $hexnumber & "   ScriptLine: " & $omyerror.scriptline & "   Description:" & $omyret[1] & @LF)
    SetError(1)
    Return
EndFunc
 
Edited by 13lack13lade
Link to comment
Share on other sites

13lack13lade,

It is telling you what is wrong.  The variable is NOT declared and is being used in func _afr1().

Also, your calls to the mail routine do not have enough parms in _afr1().

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

I cant figure this out, i simply wanted to have each function change the value of $mailfilepath1 but i couldnt work it out so i just did a work around and hard coded it for 20 files and just have each run the next one at the end of the script - at the end of the day it works and thats all i care about, perhaps ill give it another crack in condensing at a later stage. 

 

Thank you for your help though kylomas 

Edited by 13lack13lade
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...