简体   繁体   English

在 Excel 中找到一个特定的日期(使用 VBA)并粘贴到它旁边的单元格中

[英]Find a specific date in Excel (using VBA) and paste into the cell next to it

I am struggling to find a way to find a specific cell in VBA and select the cell to the right of it.我正在努力寻找在 VBA 和 select 中找到特定单元格的方法,该单元格位于其右侧。

Here is the code, with the two relevant commands in text form.这是代码,两个相关的命令都是文本形式的。 I have tried different search methods, but none are able find the date in the list.我尝试了不同的搜索方法,但没有一个能够在列表中找到日期。 Picture one is of the "Overview" sheet, picture two is the "Data" sheet.图一是“概述”表,图二是“数据”表。

Sub Save_Button()
    Range("D6:F6").Select
    Selection.Copy
    
    Dim varDate As Variant
    varDate = Range("C6").Value

    Sheets("Data").Select
        
    'Find the same date as the one saved in varDate in the sheet "Data"
    'Select the cell next to it

    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Sheets("Overview").Select
    Application.CutCopyMode = False
    Range("D6").Select
End Sub

概述 数据

Finding dates in worksheets can be difficult.在工作表中查找日期可能很困难。 underlying the date is a formatted number.日期的基础是格式化的数字。 In your code you are essentially trying to find a variant string as a number and that's not going to work.在您的代码中,您实际上是在尝试将变体字符串作为数字查找,但这是行不通的。

You need to format the string as a date type (CDate) so that you can find this within the worksheet您需要将字符串格式化为日期类型 (CDate),以便您可以在工作表中找到它

Code you should be able to adapt is below:您应该能够适应的代码如下:

Sub Foo()
    Dim ws As Worksheet: Set ws = ActiveSheet 'ThisWorkbook.Worksheets("Blah")
    
    With ws
        .Range("D6:F6").Copy
        
        Dim sDate As String: sDate = .Range("G11").Value
        Dim srcDate As Date: srcDate = CDate(Right(sDate, Len(sDate) - InStr(sDate, ",") - 1))
        
        Dim srcRange As Range: Set srcRange = .Cells.Find(srcDate)
        If Not srcRange Is Nothing Then
            srcRange.Offset(0, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
        End If
    End With
    Application.CutCopyMode = False

End Sub

Generally, you should avoid select where possible and assign the specific worksheets you want to work with in the code (it will save you headaches in the future)通常,您应该尽可能避免使用 select 并在代码中分配您要使用的特定工作表(这会在将来为您省去麻烦)

I think this is the code you want我认为这是您想要的代码

Dim foundCell As Range    
Set foundCell = Cells.Find(varDate, , , xlWhole)    
If foundCell Is Nothing Then
        MsgBox varDate & " not found"
Else
        foundCell.Offset(0, 1).Select
End If

Just put it in where you have the comment in your code.只需将其放在代码中有注释的位置即可。 This code assumes that all your dates are actually dates on the worksheets, not text.此代码假定您的所有日期实际上都是工作表上的日期,而不是文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM