简体   繁体   中英

select range of cells in VBA

within 1 row of my spreadsheet, there are the dates from 1/1/2017 to 31/12/2017 (row 2). Row 3 contains a value for each day in 2017.

Cell A1 and B1 contain dates according to which the row 2 shall be selected - so if A1 is 1/1/2017 and B1 is 31/3/2017, only these months shall be displayed in the chart that si drawn from row 2 and row 3 below (row 2 is x and row 3 is y value).

I thought about either matching or if statements. Does anybody have an idea how I could achieve that in VBA

If I'm understanding you correctly, A1 is the start day and B1 is the end day of the range you'd like to select with row 2 being all the days of 2017 starting at A2 and proceeding until the end of the year. Row 3 are the values associated with each day in row 2. Then to get the range that you want you can use the following:

Dim startIdx As Integer, endIdx As Integer
Set valRng = ActiveSheet.Range("A2:NB2")

startIdx = Application.Match(CLng(Cells(1, 1).Value), valRng, 0)
endIdx = Application.Match(CLng(Cells(1, 2).Value), valRng, 0)

Set rngSel = ActiveSheet.Range(Cells(2, 1).Offset(0, startIdx-1), Cells(2, 1).Offset(0, endIdx-1))
MsgBox ("rngSel=" & rngSel.Cells.Address)

The active ingredient that makes the value conversion work in the match statements is that the 'CLng' call gets you the day portion of the date as per this page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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