2017-10-05 136 views
0

我有一个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

RNG不被重新分配在环。对于范围(ws.cells(1,1),ws.cells(20,1))中的每个单元格,将'rng'中的每个单元格更改为'' – Zerk

+0

我试过了,但得到了“应用程序定义的或对象定义的错误“ – WaltVinegar

回答

0

它看起来对我来说,你是不是完全限定的Range

移动这里面你的WS循环,而不是它现在是。

Set rng = ws.Range("A1:A20") 
+0

我给了那一枪,并得到”对象不支持这个属性或方法“向我吐口水。 – WaltVinegar

+0

我的坏...你需要你的ws代替 - 我会编辑 – braX

+0

我已经改变了,现在我得到了“对象变量或块变量未设置”。我应该早些时候在什么地方设置ws = [something]? – WaltVinegar

0

BraX指出,我需要限定RangeFor 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 

结束子

相关问题