【问题标题】:Visual Basic for Applications QueryVisual Basic for Applications 查询
【发布时间】:2019-12-02 19:53:54
【问题描述】:

我对我的代码在 Excel 中如何运行以及如何确切知道为什么会发生这种情况存在疑问?

所以我有两个代码,我会在下面提到它们并提供执行它们的结果。

代码 1

Sub ColorLoop()

    Dim red As Long
    Dim green As Long
    Dim blue As Long
    Dim c As Range

    red = Application.WorksheetFunction.RandBetween(0, 255)
    blue = Application.WorksheetFunction.RandBetween(0, 255)
    green = Application.WorksheetFunction.RandBetween(0, 255)


    For Each c In selection
        c.Interior.Color = RGB(red, blue, green)
    Next c

End Sub

如果我运行代码一,当我在 excel 中执行选择并运行宏时,整个选择会获得一种随机颜色。

代码 2

Sub ColorLoop()

    Dim red As Long
    Dim green As Long
    Dim blue As Long
    Dim c As Range

    For Each c In selection
        red = Application.WorksheetFunction.RandBetween(0, 255)
        blue = Application.WorksheetFunction.RandBetween(0, 255)
        green = Application.WorksheetFunction.RandBetween(0, 255)

        c.Interior.Color = RGB(red, blue, green)
    Next c

End Sub

当我运行代码 2 并执行选择时,该选择中的每个单元格都有不同的颜色

我想知道为什么会这样?

【问题讨论】:

  • 在第一个 sn-p 中,您将生成一次颜色并将它们应用于每个单元格。第二,您为每个单元格生成不同的颜色。
  • 我不明白。我已经使用了 For Each 循环,它应该在两种情况下都针对选择中的每个单元格。红色、绿色和蓝色只是不应该影响的变量。
  • 但是您什么时候设置/更改这些变量的值?在第一个 sn-p 中,您要更改一次值;并且该值保持不变,直到 Sub 退出。在第二个 sn-p 中,您将多次更改值 - 对于 For Each 循环的每次迭代。

标签: excel vba


【解决方案1】:

正如 jsheenran 指出的,您只在第一个 sn-p 中运行随机颜色一次,而在第二个 sn-p 中多次运行随机颜色。

为什么 Code 1 只生成一种颜色:

Sub ColorLoop()

    Dim red As Long
    Dim green As Long
    Dim blue As Long
    Dim c As Range

    red = Application.WorksheetFunction.RandBetween(0, 255) ' Let's say the result=1
    blue = Application.WorksheetFunction.RandBetween(0, 255)' Let's say the result=10
    green = Application.WorksheetFunction.RandBetween(0, 255)'Let's say the result=20

' From here the red,blue, green are constant and every cell in the loop will have:

    For Each c In selection
        c.Interior.Color = RGB(1, 10, 20)
    Next c

End Sub

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多