goto块不工作VBA [英] goto block not working VBA

查看:152
本文介绍了goto块不工作VBA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘要:我想做一些基本的错误处理

Summary: I want to do some basic error-handling

问题:当我通过代码我的错误块数据即使没有错误也可以运行

Problem: When I step through the code my "Error" block data gets run even when there isn't an error

- 我对VBA中的错误处理非常新鲜,不明白为什么错误块中的代码运行在我指导代码进入块之外。感谢提前!

-I'm pretty new to error handling in VBA and don't understand why the code in the Error block is run aside from me directing the code to enter the block. Thanks in Advance!

代码

Function getReports()

    startJournal = Sheets("Runsheet").Range("B5")
    endJournal = Sheets("Runsheet").Range("E5")

    If startJournal = 0 Or endJournal = 0 Then

        GoTo Error

    End If

    'bunch of code

Error:
    MsgBox ("Error Statement")

End Function


推荐答案

在错误标签之前,您需要退出函数

即代码应该只有在出现错误时才打标签(eh)否则退出。

You need Exit Function before the error label.
i.e. the code should hit the label (eh) only in case of error & exit otherwise.

Function getReports() 
on error goto eh
    startJournal = Sheets("Runsheet").Range("B5")
    endJournal = Sheets("Runsheet").Range("E5")

    If startJournal = 0 Or endJournal = 0 Then

        GoTo Error

    End If

    'bunch of code

Exit Function

eh:
    MsgBox ("Error Statement")

End Function

您可以将其写为

Function getReports(startJournal as integer, endJournal as integer) as Boolean
    If startJournal = 0 Or endJournal = 0 Then
        msgbox "startJoural or endJournal should not be 0."
        exit function  '** exiting will return default value False to the caller
    End If

    'bunch of code
getReports = True
End Function

在主叫方

if getReports(Sheets("Runsheet").Range("B5"), Sheets("Runsheet").Range("E5")) then
   call faxTheReport   '** This function will be called only if getReports returns true.
end if

这篇关于goto块不工作VBA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆