简体   繁体   English

如果特定单元格包含特定文本,则VBA代码可重新复制多个单元格

[英]VBA code to recopy multiple cells if a specific cell contains a specific text

I'm new here and I apologize in advance in my question isn't clear... I couldn't find the answer after some research... 我是新来的,我事先很抱歉,我的问题还不清楚...经过研究后找不到答案...

I'm looking for a way to go through all the cells of column "R" and if one cell on a given row contains "Y", then the values of cells at columns "W","X" and "Y" will take the same value as the columns "F","G" and "H" (always at the same row). 我正在寻找一种方法来遍历“ R”列的所有单元格,如果给定行上的一个单元格包含“ Y”,则“ W”,“ X”和“ Y”列的单元格值将取与列“ F”,“ G”和“ H”相同的值(始终在同一行)。

The goal is to have a button that will execute the VBA code in order to do this (instead of having to copy/paste all the time). 目的是拥有一个将执行VBA代码的按钮,以实现此目的(而不必一直复制/粘贴)。

Thank you very much in advance for your help. 预先非常感谢您的帮助。

A poor ignorant but motivated VBA beginner... VBA初学者是一个愚昧无知但有动力的人。

Here is VBA which will do what you want. 这是VBA,它将做您想要的。 It takes advantage of the replacement operation being cells that are next to each other by using Resize . 通过使用Resize ,将替换操作作为彼此相邻的单元来利用。

Highlights 强调

  1. Iterates through each cell in column R. I used Intersect with the UsedRange on the sheet so that it only goes through cells that have values in them (instead of all the way to the end). 遍历R列中的每个单元格。我使用了Intersect与工作表上的UsedRange,以便它仅遍历其中具有值的单元格(而不是一直到最后)。
  2. Checks for "Y" using InStr . 使用InStr检查“ Y”。
  3. Replaces the contents of columns WXY with values from columns FGH. 用FGH列中的值替换WXY列中的内容。 Since they are contiguous, I did it all in one step with Resize . 由于它们是连续的,因此我使用Resize一步完成了所有工作。

Code: 码:

Sub ReplaceValuesBasedOnColumn()

    Dim rng_search As Range
    Dim rng_cell As Range

    'start on column R, assume correct sheet is open
    Set rng_search = Range("R:R")
    For Each rng_cell In Intersect(rng_search, rng_search.Parent.UsedRange)

        'search for a Y, case sensitive
        If InStr(rng_cell, "Y") > 0 Then

            'update the columns as desired
            'takes advantage of cells being next to each other
            Range("W" & rng_cell.Row).Resize(1, 3).Value = Range("F" & rng_cell.Row).Resize(1, 3).Value

        End If
    Next rng_cell
End Sub

I tested it on my end, and it works, producing the following after running: 我对它进行了最终测试,并且可以运行,并在运行后产生以下内容:

跑步后的图片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM