首页 > 解决方案 > VBA 按钮 - 基于单元格值而不是 ActiveCell

问题描述

我对 VBA 非常陌生,并尝试更新下面的代码以在单元格而不是 ActiveCell 中查找值。具体来说,我想找到值为“B”的单元格下方的行。(例如),复制下面的 3 行,然后将这 3 行粘贴+插入到复制的 3 行的正下方。实际上,我试图让我的 VBA 按钮工作而不要求用户首先单击特定单元格。只要您在正确的单元格中,我当前的基于 ActiveCell 的代码就可以正常工作。任何见解都会有所帮助。

Sub CommandButton2_Click()
    Dim NextRow As Long
    Dim I As Long

    With Range(ActiveCell.Offset(rowOffset:=2), ActiveCell.Offset(rowOffset:=0))
        NextRow = .Row + .Rows.Count
        Rows(NextRow & ":" & NextRow + .Rows.Count * (1) - 1).Insert Shift:=xlDown
        .EntireRow.Copy Rows(NextRow & ":" & NextRow + .Rows.Count * (1) - 1)
        .Resize(.Rows.Count * (1 + 1)).Sort key1:=.Cells(1, 1)
    End With
End Sub

标签: excelvba

解决方案


请测试下一个更新的代码。它将需要您需要识别的单元格的字符串/文本(在 InputBox 中)。出于测试原因,我使用了字符串“testSearch”。请把它放在 A:A 的单元格中进行识别并测试它。然后,您可以使用所需的任何字符串...

Sub testTFindCellFromString()
  Dim NextRow As Long, I As Long, strSearch As String
  Dim sh As Worksheet, actCell As Range, rng As Range

   strSearch = InputBox("Please, write the string from the cell to be identified", _
                      "Searching string", "testSearch")
   If strSearch = "" Then Exit Sub
   Set sh = ActiveSheet
   Set rng = sh.Range("A1:A" & sh.Range("A" & Cells.Rows.Count).End(xlUp).Row)
   Set actCell = testFindActivate("testSearch", rng)
   If actCell Is Nothing Then Exit Sub

   With Range(actCell.Offset(2, 0), actCell.Offset(0, 0))
        NextRow = .Row + .Rows.Count
        Rows(NextRow & ":" & NextRow + .Rows.Count * (1) - 1).Insert Shift:=xlDown
        .EntireRow.Copy Rows(NextRow & ":" & NextRow + .Rows.Count * (1) - 1)
        .Resize(.Rows.Count * (1 + 1)).Sort key1:=.Cells(1, 1)
    End With
  Debug.Print actCell.Address
End Sub
Private Function testFindActivate(strSearch As String, rng As Range) As Range
   Dim actCell As Range
   Set actCell = rng.Find(What:=strSearch)
   If actCell Is Nothing Then
        MsgBox """" & strSearch & """ could not be found..."
        Exit Function
   End If
   Set testFindActivate = actCell
End Function

推荐阅读