VBA双循环工作表和单元格

时间:2018-12-12 10:17:30

标签: excel vba excel-vba

请参见下面的代码。效果很好,但是当我尝试在所有工作表上添加额外的循环时,出现了不匹配错误13

这个作品

Sub ostdat()

Dim val As String
val = InputBox(Insert)
For Each cell In Range("d2:d20")
If cell = val Then
cell.Interior.ColorIndex = 30
End If
Next cell

End Sub

但是这个不起作用,我只添加了工作表循环

Sub ostdat()
Dim val As String
dim ws as worksheet
val = InputBox(Insert)
For Each ws In Worksheets
ws.Activate
For Each cell In Range("d2:d20")
If cell = val Then
cell.Interior.ColorIndex = 30
End If
Next cell
Next ws
End Sub

基本上,我想做的是为d列中的所有工作表和所有单元格循环,并突出显示所有单元格中值满足收件箱中条件的单元格(例如“ X130”)。

谢谢 丹

1 个答案:

答案 0 :(得分:0)

Sub ostdat()
Dim val As String
Dim ws As Worksheet
Dim c As Range

val = InputBox("Enter Number")
For Each ws In Worksheets
    For Each c In ws.Range("d2:d20")
         If c = val Then
              c.Interior.ColorIndex = 30
         End If
    Next c
Next ws
End Sub