如何根据Excel VBA中的给定日期复制单元格值

时间:2017-11-07 10:35:35

标签: excel vba excel-vba excel-2010

我附上了我的桌子。我想从A列和D列获取日期(在输入框中) 并复制相邻的单元格值(B列和E列)。然后粘贴在不同的细胞中。

例如。如果我输入日期15.10.2016和25.10.2017。然后输出必须如图所示。如果列中没有日期,则Msgbox为无效日期。帮帮我

enter image description here

1 个答案:

答案 0 :(得分:0)

这种快速方法适合您。

Sub get_money()
        a_col_last_row = ThisWorkbook.Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row
        d_col_last_row = ThisWorkbook.Worksheets(1).Cells(Rows.Count, 4).End(xlUp).Row
        data_a = InputBox("Enter 1st date")
        data_d = InputBox("Enter 2st date")
        lookup_val_a = ThisWorkbook.Worksheets(1).Cells(3, 8)
        Dim refRng_a As Range
        Dim refRng_d As Range
        Set refRng_a = Range("A2:B" & a_col_last_row)
        'data_a = Cells(3, 8).Value
        Set refRng_d = Range("D2:E" & d_col_last_row)
        'data_d = Cells(3, 9).Value
        On Error GoTo errhandler1:
        Cells(3, 8) = WorksheetFunction.VLookup(data_a, refRng_a, 2, 0)
controlback:
        On Error GoTo errhandler2:
        Cells(3, 9) = WorksheetFunction.VLookup(data_d, refRng_d, 2, 0)

        End
errhandler1:
        MsgBox "1st Value not found"
        Err.Number = 0
        Resume controlback

errhandler2:
        MsgBox " 2nd Value not found"
        Err.Number = 0
End Sub

但请注意,我使用相同的范围(H3,I3)进行输入和输出。我以为你想那样。您可以根据需要进行更改。