美好的一天,我是VBA编程的新手。需要专家帮助:)
在我输入日期并单击生成按钮后,代码将在Excel上找到日期,但我已完成此问题,这是我的代码..
Dim Rng As Range
Dim FindDate As Date
FindDate = txtDate.Value
If Trim(FindDate) <> "" Then
With Sheets("Sheet2").Range("B:B")
Set Rng = .Find(What:=FindDate, After:=.Cells(.Cells.Count), LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True)
If Not Rng Is Nothing Then
Application.Goto Rng, True
Else
MsgBox "Nothing found"
End If
End With
End If
我的下一个问题是,我需要选择日期旁边的空单元格。这是一个截屏
答案 0 :(得分:0)
要回答您的具体问题,最简单的方法是:
Rng.Offset(, 1).Select
但是,您应该知道使用日期时Find()
函数可能有点不可靠。有关详细信息和链接,请参阅此帖子:VBA, goto cell with a certain value (type: date)。由于日期是通过TextBox
输入的,因此您的案件特别容易受到风险。
我必须说你的代码看起来非常类似于该帖子的OP。如果你自己没有写代码,你真的应该对代码来源给予信任。
如果我是你,我会将您的文本框值转换为Long
然后搜索单元格值(使用.Value2
属性,其中提供日期值为Longs)以匹配Long 。代码不长,看起来像这样:
Dim src As Range
Dim findDate As Date
Dim findVal As Long
Dim cell As Range
'Define the source data range
With Sheet2
Set src = .Range(.Cells(1, "B"), .Cells(.Rows.Count, "B").End(xlUp))
End With
'Acquire search date and convert to long
findDate = CDate(UserForm1.txtDate.Value)
findVal = CLng(findDate)
'Search for date
For Each cell In src.Cells
If cell.Value2 = findVal Then
Application.Goto cell, True
'Select the next cell to the right
cell.Offset(, 1).Select
End If
Next
答案 1 :(得分:0)
你可以
使用Function
尝试返回想要的范围
Function SetRange(FindDate As Date) As Range
If Trim(FindDate) <> "" And IsDate(FindDate) Then
With Sheets("Sheet2") '<--| reference wanted sheet
With .Range("B1", .cells(.Rows.Count, 2).End(xlUp)) '<--| reference its column "B" range from row 1 down to last not empty row
On Error Resume Next '<--| if subsequent 'Find()' avoid possible subsequent statement error to stop the Function
Set SetRange = .Find(What:=FindDate, After:=.cells(.cells.Count), LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True).Offset(, 1) '<--| try finding the passed 'FindDate' in referenced range and offset 1 column to the right
End With
End With
End If
End Function
并在使用之前让您的“Main”子对Nothing
进行检查:
Option Explicit
Sub Main()
Dim Rng As Range
Set Rng = SetRange(txtDate.Text)
If Not Rng Is Nothing Then Rng.Select
End Sub