我在这里对我的代码在 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
当我运行代码二并执行选择时,该选择中的每个单元格都有不同的颜色
我想知道为什么会这样?
正如 jsheenran 指出的那样,您在第一个代码段中只运行一次随机颜色,而在第二个代码段中多次运行随机颜色。
为什么代码 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