VBA代码(设置范围,定义值,并放置颜色)

时间:2014-04-14 02:35:59

标签: excel-vba if-statement vba excel

基本上这是我现在的代码。我想创建一个模块,在任何工作表中,我设置范围,然后我定义某些值(例如:介于0,15和0,28之间)并最终在具有该数字的单元格上添加颜色。但是我得到了一些错误,而且我在最后一段时间遇到了困难。

Sub ColorFrames()

Dim range1 As Range
Dim range2 As Range
Dim valor1 As Variant
Dim valor2 As Variant
Dim Sh As Worksheet

' CODE

Set range1 = Application.InputBox(Prompt:="Please Select Range with data to be validated", Title:="Range", Type:=8)

valor1 = InputBox("Values between:")
valor2 = InputBox("and:")

If valor1 = "" And valor2 = "" Then
 ' and if < 0 and > 1... How?
    MsgBox ("Insert Values between 0 and 1! Thank you")
    Exit Sub
End If

For Each Sh In ActiveWorkbook.Sheets
    If Range(range1).Value >= valor1 And Range(range1).Value <= valor2 Then
        Sh.Interior.ColorIndex = 3
        Sh.Value = ""
    End If
Next Sh

Exit Sub
End Sub

1 个答案:

答案 0 :(得分:1)

一个选项适用于用户范围(当前选择为默认值)和循环,直到提供有效范围和条件条件为止(对于单张纸上的范围)

Sub ColorFrames()

Dim rng1 As Range
Dim rng2 As Range
Dim vArr
Dim dblV1 As Double
Dim dblV2 As Double
Dim bCondition As Boolean

Do
Set rng1 = Application.InputBox(Prompt:="Please Select Range with data to be validated", Title:="Range", Default:=Selection.Address, Type:=8)
Loop While rng1 Is Nothing

Do
vArr = Application.InputBox("Please enter lower and upper bounds, separated by a "", """, Title:="Values", Default:="0,1", Type:=2)
valor1 = Split(vArr, ",")
dblV1 = CDbl(valor1(0))
dblV2 = CDbl(valor1(1))
bCondition = (dblV1 >= 0) And (dvlv2 <= 1) And (dblV2 > dblV1)
Loop While Not bCondition

Application.ScreenUpdating = False
For Each rng2 In rng1
    If rng2.Value >= dblV1 And rng2.Value <= dblV2 Then
    With rng2
        .Interior.ColorIndex = 3
        .Value = vbNullString
    End With
    End If
Next rng2
Application.ScreenUpdating = True

End Sub