2017-04-20 29 views
0

我在每天運行的報表中有一個宏。宏的一部分改變了表的值。我正試圖在兩個值之間插入一個特定(不變)的選擇。這需要是動態的,因爲這兩個值的位置每天都會改變。Excel VBA插入基於動態參考的選擇

在兩個值低於我的代碼是:

「等待重新測試」和「加里」。我的選擇應該始終在這兩個值之間插入。當我運行宏,我得到一個錯誤代碼說

子或函數定義

和行(標有兩個星號)的亮點。 真的很感激任何幫助。

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

回答

0

感謝在發片,在下面我發現的第一個實例「加里」,改變了細胞的上方爲「英國支持」值 範圍是動態的,在這個意義上,數據可以改變,這將始終走在上面一行的第一個「加里」

Sub Find_First() 
Dim FindString As String 
Dim Rng As Range 
FindString = "Gary" 
If Trim(FindString) <> "" Then 
    With ActiveSheet.Range("B:B") 
     Set Rng = .Find(What:=FindString, _ 
         After:=.Cells(.Cells.Count), _ 
         LookIn:=xlValues, _ 
         LookAt:=xlWhole, _ 
         SearchOrder:=xlByRows, _ 
         SearchDirection:=xlNext, _ 
         MatchCase:=False) 
     If Not Rng Is Nothing Then 
       Rng.Offset(-1, 0).Value = "UK Support" 
     Else 
      MsgBox "Nothing found" 
     End If 
    End With 
    End If 
    End Sub 
0

INDIRECT是一個工作表函數。工作表函數不直接在Visual Basic中可用。

要使用VBA中的工作表函數(從Excel 2010開始),請使用WorksheetFunction對象。你的情況:

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

(正如我有Excel 2008中,我無法測試這個顯示的文檔。)

+0

喜保羅,謝謝你。 WorksheetFunction對象不適用於我,並給了我相同的錯誤(可能是因爲我在Excel 2010中)。然而,我已經管理另一種方式來選擇我想要使用的:ActiveCell.Offset(1,0).Value =「Gary」和ActiveCell.Offset(-1,0).Value =「等待重新測試」然後...然而,我現在遇到的問題是在確認了這些值之後,我選擇了不變的選擇並剪切了,我不知道如何告訴它粘貼在特定的位置。我現在使用的插件只是將其插入其下面。有小費嗎?謝謝 – Zoheil