尝试创建一个搜索按钮,当在单元格(B10)中输入时间并按下按钮时,该按钮会将值复制到工作表中。尝试了一些教程,但我一直做错了。
搜索功能在sheet1上,我的所有数据都在sheet2上。在单元格B10中输入日期和时间(m / dd / yyyy hh:mm:ss),并且应将信息复制/粘贴到单元格D10:I10中。 sheet2上的时间在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 :(得分: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
答案 1 :(得分: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