VBA

时间:2016-02-16 11:26:13

标签: excel-vba vba excel

背景 我需要帮助调整我之前通过复制粘贴编写的代码。该函数的目标是在单击目标单元格时以指定格式添加新行。

这是通过此代码[仅限摘录]实现的:

Private Sub worksheet_selectionchange(ByVal target As Range)
If Not Intersect(target, Range("G6")) Is Nothing Then
  Rows("7:7").Select
  Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
  Range("B7:F7").Select
  With Selection.Font
    .ColorIndex = xlAutomatic
    .TintAndShade = 0
  End With

到目前为止它也可以正常工作。但是现在我想再次为同一个选项卡添加此功能以用于另一个单元格区域。我现在的问题是,由于相关的行是垂直堆叠的,每当我通过原始函数添加一行时,第二个例程中定义的范围现在不再有效。

我的问题: 我可以动态定义Intersect方法的范围吗?我的想法是笨拙的,比如让第二种方法引用变量而不是固定单元格(MyRange),它由第一个例程自动更改(例如MyRange = MyRange + 1)。我该怎么办?或者还有其他方法可以实现我想要做的事情吗?

1 个答案:

答案 0 :(得分:0)

您的想法是正确的 - 预先定义变量而不是代码中的硬编码值是可维护代码的构建块之一。有很多方法可以做到这一点,包括Excel搜索关键字等等。

我对您的案例的建议是,您在Excel中查看名称管理器,并定义一个新名称,该名称引用您希望由子查看的所有单元格。如果这样做,Excel将跟踪这些单元格,就像在单元格中键入公式一样。即:如果您放入单元格C5:" = A5 + B5",并且您在B列的左侧插入一个新列,C5将自动读取" = A5 + C5" 。这样,您的VBA代码就不会发生变化,但您定义的名称中的值会发生变化。

如果不确切知道您的工作表的设置方式,以下是您实际执行此操作的示例:

    Private Sub worksheet_selectionchange(ByVal Target As Range)

    Dim MyRange As Range
    Dim CurrentRow As Integer
    Dim FormattedArea As Range 'This will hold the area of your row which you want formatted
    Const LeftColumn = 2 'this holds the left-most column of the area you want formatted...
    Const RightColumn = 6 'these hardcoded numbers will need to be changed if you want to format a different number of columns; if you have a dynamic way of determining them that would be best

    Set MyRange = Range("Possible_Areas") 'This makes MyRange = your defined, Excel-tracked name; you will need to go to the name manager in Excel and create it, listing all target cells you want included within it
    CurrentRow = Target.Row 'This will be used to find where to insert the new row, based on the current selection        

    If Not Intersect(Target, MyRange) Is Nothing Then
        Target.EntireRow.Insert 'Notice that I have removed your "selection" command - you can search this site for reasons on why ".Select" is problematic
        Set FormattedArea = Range(Cells(CurrentRow, LeftColumn), Cells(CurrentRow, RightColumn))
        With FormattedArea.Font
            .ColorIndex = xlAutomatic
            .TintAndShade = 0
        End With
    End If
End Sub