excel - 如何使用VBA根据列中的单元格内容搜索复制、插入和替换单元格数据

标签 excel vba

当用户在用户表单中输入输入时,我正在尝试复制所有包含“红色”单元格和蓝色类似单元格的 3 行。

我需要的是,当用户给出“红色”并想用“绿色”和“单击命令按钮”替换红色时,应通过复制包含红色和 的行来创建新行。用绿色替换红色 .

用户表单:

要搜索的文本框:红色

Sub Add()

sheet_name = "Sheet1"
column_name = "C"

For r = 1 To Sheets(sheet_name).Range(column_name & Rows.Count).End(xlUp).row
    If Trim(Sheets(sheet_name).Cells(r, column_name).Value) = team_name Then
        Sheets(sheet_name).Rows(r).EntireRow.Select
        Selection.Copy
        ActiveCell.Offset(1, 0).Rows("1:1").EntireRow.Select
        Selection.Insert Shift:=xlDown
        Selection.Replace What:=team_name, Replacement:=emp_name, LookAt:=xlPart, _
                    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                    ReplaceFormat:=False
    End If
Next
column_name = "E"
For r = 1 To Sheets(sheet_name).Range(column_name & Rows.Count).End(xlUp).row
    If Trim(Sheets(sheet_name).Cells(r, column_name).Value) = team_name Then
        Sheets(sheet_name).Rows(r).EntireRow.Select
        Selection.Copy
        ActiveCell.Offset(1, 0).Rows("1:1").EntireRow.Select
        Selection.Insert Shift:=xlDown
        Selection.Replace What:=team_name, Replacement:=emp_name, LookAt:=xlPart, _
                    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
                    ReplaceFormat:=False
    End If
Next
End sub


要替换的文本框:绿色
Excel 工作表如下所示:

enter image description here

输出应如下所示:
enter image description here

最佳答案

我看不出你的代码如何给出这个结果,试试这个。

Sub Add()
    Dim sh As Worksheet, c As Range, cnt As Integer, cl As Long, tN$, eN$

    Set sh = Sheets(1) 'sheet by index
    cl = 4 'column by index
    tN = "blue": eN = "green"

    With sh
        'For cl = 3 To 5 Step 2
            For Each c In .Range(Cells(1, cl), Cells(Rows.Count, cl).End(xlUp))
                If LCase(c) Like LCase(tN) & "*" Then
                    .Cells(c.Row, 1).Resize(, 6).Copy .Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(, 6)
                    .Cells(Rows.Count, 1).End(xlUp).Resize(, 6).Replace tN, eN, xlWhole, , False
                    If cnt > 3 Then Exit Sub
                    cnt = cnt + 1
                End If
            Next c
        'Next cl
    End With
End Sub

如果您对代码的输入保持一致,则不需要 LCase()。

而且,如果您想循环选择取消注释 [For cl..] 和 [Next cl] 的列,但这不会导致 3 行,因为 C 或 E 在第 6 行不包含任何团队。

关于excel - 如何使用VBA根据列中的单元格内容搜索复制、插入和替换单元格数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58950084/

相关文章:

mysql - 从 Excel 查询 MySQL 数据(反之亦然)

excel - 将我的 vba 代码的最终输出粘贴为值

vba - 如何将 ActiveX 控件复制到另一个工作表以防止控件名称更改

vba - 将一个工作表中的所有过滤数据复制到新工作簿中

vba - Excel VBA 运行时错误 1004

java - 如何使用Java从两个Excel表中使用JDBC读取数据?

vba - 为什么会弹出 "Delete Method of Range class failed"错误?

excel - 在动态 Excel 图中更改系列名称

vba - 如何避免Excel-VBA中的保存MessageBox提示?

excel - 从 Excel VBA 检查 MS Access 中是否存在查询