2015-09-10 62 views
2

如何從活動工作表上的單元格中獲取值並在非活動工作表上查找它,然後重命名該值?vba在另一個工作表上查找單元格值並重命名值?

Dim rw As Long 

    rw = ActiveCell.Row 
    If Sheets("Home").Range("D" & rw).Value = "Tender" Then 
     With Worksheets("Time Allocation").Columns("B:B") 
      Set cell = .Find(What:=.Range("B" & rw).Value, After:=Range("B" & rw), LookIn:=xlFormulas, _ 
          LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
          MatchCase:=False, SearchFormat:=False) 
      If Not cell Is Nothing Then 
       cell.Value = "test" 
      Else 
       cell.Value = "test" 
      End If 
     End With 
    End If 

我一直在使用cell.value =「測試」嘗試,但此將導致錯誤: 對象變量或塊與變量未設置

請能有人告訴我在哪裏,我錯了?

+0

你的錯誤在哪裏? –

回答

1

壞消息是,您無法在非活動工作表上使用.Select一個或多個單元格。好消息是,你絕對沒有要求你這樣做,實際上它比直接處理細胞,細胞或柱子的效率低。

Dim rw As Long, cell as range 

rw = ActiveCell.Row 
If Sheets("Sheet1").Range("D" & rw).Value = "Tender" Then 
    With Worksheets("Sheet2").Columns("B:B") 
     Set cell = .Find(What:=Sheets("Sheet1").Range("B" & rw).Value, LookIn:=xlFormulas, _ 
         LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False) 
     If Not cell Is Nothing Then 
      cell = "test" '<~~the default property is the .Value 
     Else 
      MsgBox "cannot test. not found. cell is nothing and cannot be referenced." 
     End If 
    End With 
End If 

你要在兩個工作表之間蹦跳着,並指ActiveCell property喜歡它是一個工作表,有時和其他工作其他時間的方式是有點混亂。我不是真的我在Range.Find methodWhat參數正確。

How to avoid using Select in Excel VBA macros更多的方法從依靠選擇越來越遠,並激活,以實現自己的目標。

+0

非常感謝,它的效果很好,請問我能夠在找到我需要的單元格後,如何更改單元格中的值?請查看更新後的問題 –

+0

當cell'沒有任何東西時(也許沒有找到),你可能試圖設置'cell'。如上所述,我不確定我是否有正確的搜索字詞參數。如果你認爲應該找到它,那就是開始尋找的地方。對,不是它爲Sheet2的列B中的單元格設置,它與用Sheet1的「ActiveCell.Row」分配的'rw'是同一行。 – Jeeped

+0

謝謝,但我不知道我現在做了什麼錯誤,我一直得到的是一個類型不匹配的錯誤,我甚至嘗試恢復到您給我的原始代碼,這是5分鐘前的工作,但現在它只是不斷給這個錯誤:/ –

相關問題