【问题标题】:Copy data from one column to another of the same row based on condition using VBA使用 VBA 根据条件将数据从一列复制到同一行的另一列
【发布时间】:2017-11-21 07:00:39
【问题描述】:

我有一个 Excel 文件,其中包含一个名为 in-out 的工作表。在工作表中,有 4 列被数据占用,另外两列是空白。

col A : 输入/输出名称

col B : 输入名称(空白)

col C : 输出名称(空白)

col D : 端口使用的名称

col E : 设置输入/设置输出

col F : 值

我需要做的任务是检查从 1 到最后的每一行(大约 90000 行并将增加),如果 col E 中的数据等于 set_input,则将 col A 中的数据复制到 col 中的单元格B,如果 col E 中的数据等于 set_output,则将 col A 中的数据复制到 col B 中的单元格。

我可以知道如何启动 VBA 脚本,我应该先找到最后一行,以便程序循环到最后使用的行吗?是否可以逐行检查并根据条件复制数据?

我开始写下面的脚本,结果卡住了。

Sub Test()

Dim LastRow As Long
Dim x As Integer

With Worksheets("in-out")
  LastRow = .Cells(Rows.Count, "E").End(xlUp).Row
    .Range("E2:E" & LastRow).Select
  For x = Range("E2") To LastRow
  If x = "set_input_" Then

End With

End Sub    

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    试试下面的代码,它会遍历 E 列值的所有单元格:

    • 如果 A 列中单元格的值为 "set_input_" ,则它将值从 "A" 列复制到 "B" 列。
    • 如果 A 列中单元格的值为 "set_output_" ,它会将值从 "A" 列复制到 "C" 列。

    注意:没有必要(最好避免)使用Select,你不需要.Range("E2:E" & LastRow).(选择整个范围,而是使用完全限定的对象。

    代码

    Option Explicit
    
    Sub Test()
    
    Dim LastRow As Long
    Dim x As Long
    
    With Worksheets("in-out")
        LastRow = .Cells(Rows.Count, "E").End(xlUp).Row
    
        For x = 2 To LastRow
            If .Range("E" & x).Value = "set_input_" Then
                .Range("B" & x).Value = .Range("A" & x).Value
            ElseIf .Range("E" & x).Value = "set_output_" Then
                .Range("C" & x).Value = .Range("A" & x).Value
            End If
        Next x
    End With
    
    End Sub
    

    【讨论】:

    • 嗨@Shai Rado,感谢您的说明,代码有效。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2018-08-14
    • 2022-01-25
    • 2019-10-31
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多