Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

VBA - Copy certain range between two dates in the same row

0

Hello everyone,

I've been struggling quite a lot with this. I am trying to copy a certain range (the range that is set between two dates in the same row). 

I've found a lot of documentation on how to copy a range between dates that are in the same column. My dates are in the same row. (Team planning calendar) 

What I need: 

1. I will set a start date and an end date on the sheet "test" 

2. I press a button that finds these dates (on the sheet "Kursplanung") and copys everything inbetween (only until a certain row -> in this case row 12) 

3. The last part - pasting onto the selected sheet, should be pretty easy to do. I could do that myself. 

Is there any way to do possibly do this? 

Thanks in advance!

Sincerely

Luca

Answer
Discuss

Answers

0
Selected Answer

Judging by its result, the code below seems like a far way from what you probably expect but it does show you how to select the range you want to copy. Therefore it should be helpful. The problem isn't with the selection of the source but with the formatting of the target.

Sub findAndCopy()
    ' 169

    Dim Kursplanung     As Worksheet, Test As Worksheet
    Dim DateRng         As Range
    Dim DayStart        As Variant
    Dim DayEnd          As Variant

    ' Set sheets
    Set Kursplanung = Worksheets("Kursplanung")
    Set Test = Worksheets("test")

    With Kursplanung
        Set DateRng = .Range(.Cells(5, 1), .Cells(5, .Columns.Count).End(xlToLeft))
        DayStart = Application.Match(Test.Cells(5, "C").Value2, DateRng, 0)
        DayEnd = Application.Match(Test.Cells(6, "C").Value2, DateRng, 0)
        If IsError(DayStart) Or IsError(DayEnd) Then Exit Sub

        .Range(.Cells(6, DayStart), .Cells(12, DayEnd)).Copy Test.Cells(5, "E")
    End With
End Sub
Discuss

Discussion

Thank you! Can't we just copy the formatting too? This code works pretty good so far! I'll try to adjust it. Thank you so much for your help!
zwergenheber (rep: 4) Feb 9, '21 at 11:36 am
Seems to me that with the code from @Variatus, the formatting is copied too so you only need to adjust the row heights/ column widths in Test to match.
John_Ru (rep: 6152) Feb 9, '21 at 1:51 pm
Thank you guys so much! It works great with adjusted formatting! Perfect!
zwergenheber (rep: 4) Feb 10, '21 at 3:03 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login