Excel VBA基于动态引用插入选择

时间:2017-04-20 10:03:00

标签: excel vba excel-vba insert

我在每天运行的报告中都有一个宏。宏的某些部分会更改表的值。我试图在两个值之间插入一个特定的(未更改的)选择。这需要是动态的,因为这两个值的位置每天都会改变。

在下面的代码中,这两个值是:

"等待重新测试"和"加里"。我的选择应始终在这两个值之间插入。当我运行宏时,我得到一个错误代码

  

子或功能未定义

和行(标有两个星号)突出显示。 真的很感激任何帮助。

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    Dim xRg As Range
    Dim xTxt As String
    Dim xCell As Range
    Dim xEndRow As Long
    Dim I As Long
    Dim G As Long
    Dim H As Long
    Dim R As Long
    Dim P As Long
    Dim F As Long
    Dim L As Long
    Dim A As Long
    Dim U As Long
    Dim C As Long

    On Error Resume Next
    If ActiveWindow.RangeSelection.Count > 1 Then
      xTxt = ActiveWindow.RangeSelection.AddressLocal
    Else
      xTxt = ActiveSheet.UsedRange.AddressLocal
    End If
lOne:

Set xRg = Application.InputBox("Select range:", "Kutools for Excel", xTxt, , , , , 8)

If xRg Is Nothing Then Exit Sub

If xRg.Columns.Count > 1 Or xRg.Areas.Count > 1 Then
        MsgBox " Multiple ranges or columns have been selected ", vbInformation, "Kutools for Excel"
        GoTo lOne
End If

    xEndRow = xRg.Rows.Count + xRg.Row
    Application.ScreenUpdating = False
    For I = xRg.Rows.Count To 1 Step -1
        If xRg.Cells(I) = "Awaiting Retest" Then
           xRg.Cells(I).EntireRow.Cut
           Rows(xEndRow).Insert Shift:=xlDown
        End If
        If xRg.Cells(I) = INDIRECT(Address(**Row**() - 1, Column())) = "Awaiting Retest" And INDIRECT(Address(**Row**() + 1, Column())) = "Gary" Then
           Rows.Range("TEST").Select
           Application.CutCopyMode = False
           Selection.Cut
           Selection.Insert Shift:=xlDown
        End If

Screenshot of VBA Code

1 个答案:

答案 0 :(得分:0)

INDIRECT是一个工作表函数。 Visual Basic中无法直接使用工作表函数。

要在VBA中使用工作表函数(来自excel 2010),请使用WorksheetFunction对象。在你的情况下:

xRg.Cells(I) = WorksheetFunction.Indirect(...

(由于我有Excel 2008,我无法对此进行测试。请参阅文档。)