Isp*_*nic 1 excel vba excel-vba
假设我有一列数字,例如:
1; -1; 5; 4; 3; -3; -3; 3; -4; 7.
我想制作一个可以突出显示所有正负数对(例如1和-1)的宏,同时还考虑到可以出现多对的事实(例如3和-3都出现两次).此外,我希望能够输入我想要使用的范围.
对于上面的示例,除5和7外,所有数字都应突出显示.
这是我到目前为止所提出的
Sub HighlightExercise()
Set myRange = Application.InputBox(prompt:="Sample", Type:=8)
myRange.Interior.ColorIndex = 2
For Each cell In myRange
If cell.Interior.ColorIndex = 30 Then Next
Set CValue = Cell.Value
myRange.Select
Set CFind = Selection.Find(What:=CValue.Value * -1, After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False)
If CFind.Value = Null Then Next
If CFind.Interior.ColorIndex = 30 Then Next
CFind.Interior.ColorIndex = 30
CValue.Interior.ColorIndex = 30
Next
End Sub
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,它表示"编译错误,下一个没有For"但For条件就在那里.我试过"Next Cell"和"Next iteration"但仍然没有.我得不到什么?
代替:
If cell.Interior.ColorIndex = 30 Then Next
您需要测试相反的情况并允许它运行代码,如果为true:
If cell.Interior.ColorIndex <> 30 Then
Run Code Online (Sandbox Code Playgroud)
您也可以.Value在许多不允许的地方使用它:
Set CValue = Cell.Value
应该:
Set CValue = Cell
Run Code Online (Sandbox Code Playgroud)
但实际上并不需要,因为Cell已经是一个范围.
不要忘记声明你的变量:
Dim myRange As Range
Dim cell As Range
Dim cfind As Range
Run Code Online (Sandbox Code Playgroud)
同样在Find中,我们想要从当前单元格中搜索以进行更改:
After:=ActiveCell
至
After:=cell
Run Code Online (Sandbox Code Playgroud)
避免.Select在范围内使用你想做的事情:
Set cfind = myRange.Find...
Run Code Online (Sandbox Code Playgroud)
尝试:
Sub HighlightExercise()
Dim myRange As Range
Dim cell As Range
Dim cfind As Range
Set myRange = Application.InputBox(prompt:="Sample", Type:=8)
myRange.Interior.ColorIndex = 2
For Each cell In myRange
If cell.Interior.ColorIndex <> 30 Then
Set cfind = myRange.Find(What:=cell.Value * -1, After:=cell, LookIn:= _
xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False)
If Not cfind Is Nothing Then
If cfind.Interior.ColorIndex <> 30 Then
cfind.Interior.ColorIndex = 30
cell.Interior.ColorIndex = 30
End If
End If
End If
Next
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
475 次 |
| 最近记录: |