I am very new to VBA and trying to update the code below to look for a value within a cell rather than ActiveCell. Specifically, I want to find the row below a cell with a value of "B." (eg), copy the 3 rows below, and paste+insert those 3 rows directly beneath the copied 3 rows. Effectively, I am trying to get my VBA button to work without asking users to first click into a specific cell. My current code, based on ActiveCell, is working well as long as you are in the correct cell. Any insight would be helpful.
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
Please, test the next updated code. It will require the string/text of the cell you need to identify (in an InputBox). For testing reason, I used the string "testSearch". Please, put it in the cell of A:A to be identified and test it. Then, you can use whatever string you need...
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.