我有一个带有单个按钮的xlsm文件,当单击该按钮时,应该打开一个单独的工作簿并搜索所有包含的工作表以查找特定颜色的单元格。 问题是,它不是搜索其他工作簿的工作表,而是搜索自己。我是VBA的新手,感觉我已经在互联网上试了6次。我在这里做错了什么?
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim holdCount As Integer
Dim cellColour As Long
Dim cell As Range, rng As Range
Set wb = Workbooks.Open("blahblahblah.xls")
Set rng = Range("A1:A20")
holdCount = 0
cellColour = RGB(255, 153, 0)
For Each ws In wb.Worksheets
For Each cell In rng
If cell.Interior.Color = cellColour Then
holdCount = holdCount + 1
End If
Next cell
Next ws
MsgBox "found " & holdCount
End Sub
答案 0 :(得分:0)
在我看来,您并不完全符合Range
将其移动到ws循环内部而不是现在的位置。
Set rng = ws.Range("A1:A20")
答案 1 :(得分:0)
BraX指出我需要在Range
循环中限定For Each ws
,所以这里是固定且有效的代码。同样,归功于Brax。
Private Sub CommandButton1_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim holdCount As Integer
Dim cellColour As Long
Dim cell As Range, rng As Range
Set wb = Workbooks.Open("blahblahblah.xls")
holdCount = 0
cellColour = RGB(255, 153, 0)
For Each ws In wb.Worksheets
With ws
Set rng = ws.Range("A1:A20")
For Each cell In rng
If cell.Interior.Color = cellColour Then
holdCount = holdCount + 1
End If
Next cell
End With
Next ws
MsgBox "found " & holdCount
End Sub