应用选择案例 [英] Applying Select Case

查看:88
本文介绍了应用选择案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前代码如下:

For Each s In myReport.Sheets
    If s.Name = "Data" Then
        s.Activate
        Excel.ActiveWindow.Zoom = 80
    End If
    If Left(s.Name, 7) = "Charts_" Then
        s.Activate
        Excel.ActiveWindow.Zoom = 77
    End If
    If s.Name = "definitions" Then
        s.Activate
        Excel.ActiveWindow.Zoom = 75
    End If
    If s.Name = "Summary" Then
        s.Activate
        Excel.ActiveWindow.Zoom = 71
    End If
Next

使用选择案例 ?我不确定如何在此上下文中应用 VBA 选择案例。

Could this be made more efficient using a Select Case? I'm unsure how to apply VBA version of select case in this context.

推荐答案

这是我尝试使用选择案例 - 虽然我喜欢KazJaw的如果/ ElseIf ,因为它是更加灵活。

Here's my attempt using Select Case - though I'd prefer KazJaw's If/ElseIf, as it is even more flexible.

Dim z as Integer

For Each s in myReport.Sheets
    Select Case UCase(s.Name)
       Case "DATA": z = 80
       Case "DEFINITIONS": z = 75
       Case "SUMMARY": z = 71
       Case Else:
           If Left(s.Name, 7) = "Charts_" Then 
               z = 77
           Else
               z = 0
           End If
    End Select
    If z Then
        s.Activate
        ActiveWindow.Zoom = z
    End If
Next s

或者,您可以使用以下技巧创建非常灵活的选择案例语句:

Alternatively, you can create a very flexible Select Case statement with the following trick:

For Each s In ThisWorkbook.Sheets
    Select Case True
       Case s.Name = "Data":             z = 80
       Case Left(s.Name, 7) = "Charts_": z = 77
       Case s.Name = "Defintions":       z = 75
       Case s.Name = "Summary":          z = 71           
       Case Else:                        z = 0
    End Select
    If z Then
        s.Activate
        ActiveWindow.Zoom = z
    End If
Next s

从两个示例可以看出,第一个选择案例允许您执行每个比较的中心代码(例如 UCase ,这是一个很好的做法),而第二个给你充分的灵活性 - 但最终没有其他的,然后一个如果/ ElseIf /... statement!

As you can see from the two examples, the first Select Case allows you to execute a central code for each comparison (e.g. the UCase, which is a good practise anyway), while the second gives you full flexibility - but is in the end nothing else then an If/ElseIf/... statement!

这篇关于应用选择案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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