简体   繁体   中英

Excel VBA: how to select specific rows to be affected by on-selection

Using Excel 365 on desktop, I am trying to make the height of the selected row change to 280:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Target.Calculate   
    For Each r In ActiveWindow.RangeSelection.Rows
        r.RowHeight = 280
    Next r
End Sub

I want the code to only affect the selection in specific rows ("4:499"). I tried using the following code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rng As Range: Set rng = Range("4:499")
    Target.Calculate
    For Each r In ActiveWindow.RangeSelection.Rows
        r.RowHeight = 280
    Next r
    If intersect(Target, rng) Is Nothing Then Exit Sub
End Sub

How do I specify the range of rows?

To just have the code run if the cell selected is within a certain range, you can compare the Row property of the selected range with the row-numbers you wish it to be within. In your case something like:

If Target.Row >= 4 And Target.Row <= 499 Then
    # Your code
EndIf

To account for all edge cases and always only affect the intersection of the selected range and your desired specific rows , you can use the following algorithm:

  1. Create the intersection of your desired range and the user's selection
  2. Check if this intersection is empty
  3. If not, apply your desired actions to the intersection

The following code demonstrates this while also avoiding to loop over all cells in the affected range by setting the row height directly for all rows.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

   Dim newHeight As Long: newHeight = 280
   Dim minRow As Long: minRow = 4
   Dim maxRow As Long: maxRow = 499

   ' Define the range of rows we want the resizing to happen on
   Dim applicableRange As Range
   Set applicableRange = Range(Rows(minRow), Rows(maxRow))

   ' Intersect that with the range of the selection
   Dim affectedRange As Range
   Set affectedRange = Intersect(Target, applicableRange)

   ' If the intersection contains any rows (i.e. is not empty), apply the changes
   If Not affectedRange Is Nothing Then

      affectedRange.Calculate
      affectedRange.RowHeight = newHeight

   End If

End Sub

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