Excel宏 - 选择案例

时间:2011-05-02 07:28:55

标签: excel select excel-vba case vba

我还没有人发布过这个问题,如果我错了就不要开枪! :P

我有一个怪物,如果其他结构大约300-400行。使用外壳结构,我可以将其降低到100或更低。麻烦的是,您只能找到具有固定值而不是单元格值的选择案例。

代码的作用是什么?

C17-C22可以赋值1或0.如果值为1,则将文本复制到工作表中,如果值为0,则不会发生任何操作。

Select case ???
   Case "C17" = 1
      show me text!!
   Case "C18" = 1
      show me text!!
   ...
End select

我知道我可以用不同的选择案例来做这件事

Select case "C17".value
   Case 1
      show me text!!
End select
...

但我认为应该可以在一个BIG Select Case中进行,而不是多个Select Case。

非常感谢!

2 个答案:

答案 0 :(得分:1)

Select语句用于区分变量可以有的不同值。即Select Case是等式的左侧,以下case个等式是等式的不同右侧。我认为你的任务不是Select case

的工作

如果每个单元格的情况相同,则遍历您的范围并对每个单元格执行选择。但是如果你只检查单元格是0还是1,那么使用if

类似的东西:

For each c in SourceRange
  if c.value Then
      ...
  end if
Next c

答案 1 :(得分:1)

听起来你试图将问题塞进Select Case构造中,让自己的生活变得更加复杂。顺便说一下,Select Case 几乎If Else完全相同;区别主要是化妆品,你原则上可以use them interchangeably

为什么不这样:

Dim i As Long
Dim varFlags As Variant
Dim varText As Variant

' Load flags from sheet.
varFlags = Range("C17:C22")

' Load text associated with each flag. Here I'll just hardcode them. 
varText = Array("Text17", "Text18", "Text19", "Text20", "Text21", "Text22")

For i = LBound(varFlags, 1) To UBound(varFlags, 1)
    If varFlags(i, 1) = 1 Then
        'It's a 1. Copy the relevant text. 
        'Here I just MsgBox it.
        MsgBox varText(i - 1) 'Sorry for the i-1, my varText array is zero-based!
    Else
        'It's not a 1. Do nothing.
    End If
Next i
相关问题