vba - 当值更改VBA时,从调色板中查找colorindex为行着色
问题描述
代码:
Public Sub HighLightRows()
Dim i As Integer
i = 2
Dim c As Integer
c = 2 'Color 1
'Dim colorIndex As XlColorIndex: colorIndex = Application.Dialogs(xlDialogEditColor).Show(10)
'MsgBox colorIndex
Do While (Cells(i, 1) <> "")
If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)
If c = 2 Then
c = 24 'color 2
Else
c = 2 'color 1
End If
End If
Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.colorIndex = c
i = i + 1
Loop
End Sub
此代码完美运行,并在列中的值更改时更改颜色。但是颜色是在代码中指定的。我希望用户选择他/她选择的颜色。
我用上面的代码得到的输出:我想要代码做什么:
打开调色板。用户选择一种颜色。颜色索引被传递给一个变量。当值更改时,行将交替显示为白色和所选颜色。
例如。如果用户从调色板中选择蓝色,则行将是具有交替组的蓝白色。如果用户从调色板中选择绿色,则行将是具有交替组的绿色和白色。
我尝试包含此代码:
Dim colorIndex As XlColorIndex: colorIndex = Application.Dialogs(xlDialogEditColor).Show(10)
MsgBox colorIndex
调色板完美打开,但MsgBox colorIndex
给我 -1 作为输出。
我似乎无法让它工作。代码有什么变化。?
解决方案
如果选择了颜色并且用户按下了取消,则Dialogs(xlDialogEditColor)
返回。要获得选定的颜色,请使用下面的示例。True = -1
False = 0
ActiveWorkbook.Colors(10)
Option Explicit
Public Sub ColorPaletteDialogBox()
Dim lcolor As Long
If Application.Dialogs(xlDialogEditColor).Show(10) = True Then
'user pressed OK
lcolor = ActiveWorkbook.Colors(10)
ActiveCell.Interior.Color = lcolor
Else
'user pressed Cancel
End If
End Sub
因此,对于您的循环,您可以使用类似...</p>
Option Explicit
Public Sub HighLightRows()
Dim c As Integer
c = 2 'Color 1
Dim i As Long 'integer is too small for row counting!
i = 2
If Application.Dialogs(xlDialogEditColor).Show(10) = True Then
Do While (Cells(i, 1) <> "")
If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)
If c = 2 Then
c = 10 'color 2
Else
c = 2 'color 1
End If
End If
Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.colorIndex = c
i = i + 1
Loop
Else
'user pressed Cancel
End If
End Sub
推荐阅读
- python - Tkinter 打字动画
- java - Mongodb Java SDK 不使用 @BsonProperty 作为字段名
- powerbi - 对默认视图为受限视图的 Power BI 报表实施对象级安全性
- c# - 仅在 C# 中创建单选按钮 Xamarin 表单
- python - 根据列名合并两列
- laravel - 为什么当我使用 Auth 时 Auth 外观起作用,而其他类(如 Request)在我编写整个目录之前不起作用
- algorithm - 计算过去 X 秒内数据流中元素的平均数量
- java - 如何使用 Discord4J 获取公会成员列表?
- google-chrome - 如何修复 Chrome 控制台中的错误:不推荐使用 chrome.loadTimes()?
- python - 在 Python 中加速插值