簡體   English   中英

VBA 按鈕 - 基於單元格值而不是 ActiveCell

[英]VBA button - based on a cell value rather than 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

請測試下一個更新的代碼。 它將需要您需要識別的單元格的字符串/文本(在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM