Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA:如何选择在选择时受影响的特定行_Excel_Vba - Fatal编程技术网

Excel VBA:如何选择在选择时受影响的特定行

Excel VBA:如何选择在选择时受影响的特定行,excel,vba,Excel,Vba,使用桌面上的Excel 365,我试图将所选行的高度更改为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 我希望代码只影响特定行中的选择(“4:499”)。我尝试使用以下代码

使用桌面上的Excel 365,我试图将所选行的高度更改为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
我希望代码只影响特定行中的选择(“4:499”)。我尝试使用以下代码:

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

如何指定行的范围?

要在选定单元格位于某个范围内时运行代码,可以将选定范围的
属性与希望其位于某个范围内的行号进行比较。在您的情况下,类似于:

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

如果Target.Row>=4和Target.Row要考虑所有边缘情况,并且始终只影响选定范围与所需特定行的交集,可以使用以下算法:

  • 创建所需范围和用户选择的交点
  • 检查这个十字路口是否是空的
  • 如果没有,请将所需操作应用于交叉口
  • 下面的代码演示了这一点,同时通过直接为所有行设置行高来避免在受影响范围内的所有单元格上循环

    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
    
    好简单!这种方法唯一的问题是,它不能正确地解释超出所需行范围的选择。因此,如果您选择行
    498:510
    ,那么所有这些行的大小都将调整,而不仅仅是第498行和第499行。或者,如果选择
    2:5
    ,则不会调整行的大小,而是调整4和5的大小。也要注意解释这些案例。