2017-02-17 61 views
0

嘗試創建一個搜索按鈕,當在單元格(B10)中輸入時間並按下按鈕時,將會將值複製到工作表。嘗試了幾個教程,但我一直在做錯誤的事情。使用時間vba的搜索按鈕

搜索功能在sheet1上,我的所有數據都在sheet2上。在單元格B10中輸入日期和時間(m/dd/yyyy hh:mm:ss),並將信息複製/粘貼到單元格D10:I10中。表2中的時間在A中,而我想要的數據是B到G.搜索只應返回一行值。

我在代碼中做了什麼錯誤?

Sub search() 

Dim erow As Long 
Dim ws As Worksheet 
Dim lastrow As Long 
Dim count As Integer 

lastrow = Sheets("Sheet2").Cells(Rows.count, 1).End(xlUp).Row 

For x = 2 To lastrow 

If Sheets("Sheet2").Cells(x, 1) = Sheet1.Range("B10") Then 
Sheet1.Range("D10") = Sheets("Sheet2").Cells(x, 2) 
Sheet1.Range("E10") = Sheets("Sheet2").Cells(x, 3) 
Sheet1.Range("F10") = Sheets("Sheet2").Cells(x, 4) 
Sheet1.Range("G10") = Sheets("Sheet2").Cells(x, 5) 
Sheet1.Range("H10") = Sheets("Sheet2").Cells(x, 6) 
Sheet1.Range("I10") = Sheets("Sheet2").Cells(x, 7) 
End If 

End Sub 
+0

'Rows'在'Rows.Count'(隱含)指的是什麼工作是有效的。如果這不是'Sheet2',並且你的代碼有效,那麼它運氣不好。最好限定「Rows」調用它正在查看的工作表。您還應該從'Worksheets'集合中獲取工作表引用,因爲'Sheets'集合可以包含圖表和其他非工作表表單類型。 –

+1

您的'For'循環需要'Next'令牌來終止。 –

回答

1

Sheet1聲明爲變量嗎?我沒有看到你設置它的任何地方。試試這個:

Sub search() 

    Dim erow As Long 

    Dim wbTarget as Workbook 
    Dim wsTarget as Worksheet 

    Dim wsSource as Worksheet 

    Dim ws As Worksheet 
    Dim lastrow As Long 
    Dim count As Integer 

    Dim r as Range 

    Set wbTarget = ThisWorkbook 
    Set wsTarget = wbTarget.Sheets("Sheet1") 

    Set wsSource = wbTarget.Sheets("Sheet2") 

    lastrow = wsSource.Cells(wsSource.Rows.count, 1).End(xlUp).Row 

    For x = 2 To lastrow 

     If wsSource.Cells(x, 1) = wsTarget.Range("B10") Then 
      Set r = wsSource.Cells(x, 2).Resize(8, 1) 
      wsTarget.Range("D10:I10").Value = r.Value 
      Set r = Nothing 
     End If 
    Next 

End Sub 
+0

我不知道爲什麼一些代碼是紅色的,但這應該工作。 –

+1

'Sheet1'可以假定爲'ThisWorkbook'中工作表的'CodeName',而使用這些全局範圍的「free」對象引用的IMO是引用工作表的最可靠的方法 - 如果用戶重命名代碼不會中斷(與'Sheets(「SheetName」)'相反),並且重構工具(如[Rubberduck](http://rubberduckvba.com))可以更好地跟蹤對它的引用,這會使它們重構友好(即可以重新命名而不會破壞任何東西)。 –

+2

修正了下一個。我對CodeNames毫無頭緒,所以感謝您指出了這一點。這實際上是非常有意義的,並且在處理表名易於被編輯的文件時使用SheetNames肯定更好。我一定會在將來使用CodeNames! –

0

你可以嘗試:

Option Explicit 

Sub search2() 
    Dim myCell As Range, foundCell As Range 

    Set myCell = Worksheets("Sheet01").Range("B10") 
    With Worksheets("Sheet02") 
     Set foundCell = .Range("A1", .Cells(.Rows.count, 1).End(xlUp)).Find(what:=myCell.Value, LookIn:=xlFormulas, lookat:=xlWhole) '<--| try and find wanted date/time 
     If Not foundCell Is Nothing Then myCell.Offset(, 2).Resize(, 6).Value = foundCell.Offset(, 1).Resize(, 6).Value '<--| if found then copy its adjacent 6 columns to Sheet1 "D10:E10" range 
    End With 
End Sub