excel - 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
解决方案
请测试下一个更新的代码。它将需要您需要识别的单元格的字符串/文本(在 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
推荐阅读
- python - 使用 FloodFill 后 OpenCV HoughCircles 无法正常工作
- laravel - Laravel 7 FormRequest 更新没有只读字段
- python - 根据列值合并 2 个数据框
- angular - 如何在 Angular 9 中排除未使用的 TS 文件
- c# - 有没有办法在 C# 中使用正则表达式在字符串中的某个位置插入符号?
- javascript - 悬停时带有弹出窗口的图像映射
- android - 类 Result 需要一种类型参数
- machine-learning - 是否可以通过 CPU 多处理来拟合 Keras 模型?
- angular - 哪个是为 Angular 应用程序执行谷歌分析的最佳 npm 包?
- laravel - 如何使用 laravel 获取 Camscanner 生成的元数据 PDF 文件?