2017-03-05 944 views
-2

美好的一天,我是VBA编程的新手。需要专家:)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

当找到日期时,'Rng'将被设置为匹配的单元格。如果你想查看值,或者只是使用诸如Cells(rsg.row,rng.column).value =“向左看”,你可以引用'rng.Row'和'rng.Column'。或者你可以使用'Offset'来'rng'。 –

回答

0

为了回答您的具体问题,最简单的方法是:

Rng.Offset(, 1).Select 

但是,您应该意识到使用日期时的Find()函数可能有点不可靠。看到这篇文章的更多信息和链接:VBA, goto cell with a certain value (type: date)。由于日期是通过TextBox输入的,因此您的情况特别容易受到风险。

我不得不说你的代码看起来非常类似于那篇文章的OP。如果你没有自己写,你真的应该信任代码来源。

如果我是你,我会将你的文本框值转换为Long,然后搜索单元格值(使用提供日期值作为长整数的.Value2属性)作为匹配的长整数。代码是不是更长的时间,可能是这样的:

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 
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 
    
  • ,有你的“主“在使用前对照Nothing进行核对:

    Option Explicit 
    
    Sub Main() 
        Dim Rng As Range 
    
        Set Rng = SetRange(txtDate.Text) 
        If Not Rng Is Nothing Then Rng.Select 
    End Sub 
    
+0

@BartD,如果我的答案解决了您的问题,请点击答案旁边的复选标记以接受答案,将其从灰色变为灰色。谢谢 – user3598756

+0

@BartD,有机会从您那里获得反馈? – user3598756