给定2个日期时查找单元格范围

Cha*_*rld 2 excel vba

我有一张桌子,数字从1到10。(从D2到M2)

假设A1中03/09/2019

并且在B1中06/09/2019

AND在C1中Hello

A栏我有从A3到A10的多个单词系列

这是Excel表的示例

在此处输入图片说明

我想做的是:在A列中搜索Student一词,找到它后,从A1-> 3A2-> 6中获取数字,并在单元格中的C1中写上Hello这个词。在找到的单词Student的行中转到3至6

所以我的输出是这样的:

在此处输入图片说明

到目前为止,这是我的代码:

Dim Cell As Range
Columns("A:A").Select 
Set Cell = Selection.Find(What:="Student", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

If Cell Is Nothing Then
    MsgBox "Word not found"

Else
    MsgBox "Word found"
End If
Run Code Online (Sandbox Code Playgroud)

基本上我可以找到单词Student,但是不知道如何在3到6之间的单元格中写Hello

Dea*_*ean 5

有关以下代码的一些注意事项(未经测试!)。

1)使用VBA时,请始终尝试使用工作表限定符。这样可以使代码更简洁,减少不必要错误的空间

2)使用.Find方法时,我使用的LookAt:=xlWhole原因是,如果您未明确定义此方法,则您的代码将使用在Excel中将使用的最后一个已知方法。同样,显式定义留下的错误余地更少。

3)尝试在编码时包含错误处理。这提供了“断点”,以便将来进行调试。

4)您可以使以下内容更具动态性。但是,我将由您自己决定如何做!

Option Explicit

Sub SearchAndBuild()

    Dim rSearch As Range
    Dim lDayOne As Long, lDayTwo As Long
    Dim lColOne As Long, lColTwo As Long
    Dim sHello As String
    Dim wsS1 As Worksheet
    Dim i As Long


    'set the worksheet object
    Set wsS1 = ThisWorkbook.Sheets("Sheet1")
    'store variables
    lDayOne = Day(wsS1.Range("A1").Value)
    lDayTwo = Day(wsS1.Range("B1").Value)
    sHello = wsS1.Range("C1").Value

    'find the student first
    Set rSearch = wsS1.Range("A:A").Find(What:="Student", LookAt:=xlWhole)

    'error handling
    If rSearch Is Nothing Then
        MsgBox "Error, could not find Student."
        Exit Sub
    End If

    'now loop forwards to find first date and second date - store column naumbers
    'adjust these limits where necessary - can make dynamic
    For i = 4 To 13
        If wsS1.Cells(2, i).Value = lDayOne Then
            lColOne = i
        End If
        If wsS1.Cells(2, i).Value = lDayTwo Then
            lColTwo = i
            Exit For
        End If
    Next i

    'now merge the range
    wsS1.Range(wsS1.Cells(rSearch.Row, lColOne), wsS1.Cells(rSearch.Row, lColTwo)).Merge

    'set the vvalue
    wsS1.Cells(rSearch.Row, lColOne).Value = sHello

End Sub
Run Code Online (Sandbox Code Playgroud)

这只是解决问题的一种方法。希望这有助于您的理解!