Excel VBA - 搜索范围 - 如果单元格包含文本,则复制单元格 - 粘贴偏移量 2,1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34954318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:11:38  来源:igfitidea点击:

Excel VBA - Search Range - If Cell Contains Text Then Copy Cell - Paste Offset 2,1

excelexcel-vbavba

提问by Ronnie G.

I'm attempting to simplify an excel sheet I work with on a weekly basis.

我正在尝试简化我每周使用的 Excel 表格。

I'm trying to create a VBA Macro that would do the following:

我正在尝试创建一个可以执行以下操作的 VBA 宏:

  1. Search Column C for any Cells that contain Text, If Blank Ignore It
  2. If text is found in a Cell, Copy That Cell, Paste the Contents Offset (2,1)
  1. 在 C 列中搜索包含文本的任何单元格,如果为空白则忽略它
  2. 如果在单元格中找到文本,则复制该单元格,粘贴内容偏移量 (2,1)

Any help anyone can give me, I would greatly appreciate. I have searched for other macros and have attempted to modify them for my use to no avail.

任何人都可以给我任何帮助,我将不胜感激。我搜索了其他宏并尝试修改它们以供我使用但无济于事。

    **Example Before Macro**
  A       B       C       D       E
1                 Hi
2                 Test
3
4                 Done
5
6

**Example After Macro Has Been Run**
  A       B       C       D       E
1                 Hi
2                 Test
3                         Hi
4                 Done    Test
5
6                         Done

Current Code:

当前代码:

Sub CopyC()  
  Dim SrchRng As Range, cel As Range 
  Set SrchRng = Range("C1:C10") 

  For Each cel In SrchRng 
    If InStr(1, cel.Value) > 0 Then 
      cel.Offset(2, 1).Value = "-" 
    End If 
  Next cel 
End Sub

回答by Scott Craner

You are Close:

你很近:

Sub CopyC()
Dim SrchRng As Range, cel As Range
Set SrchRng = Range("C1:C10")
For Each cel In SrchRng
    If cel.Value <> "" Then
        cel.Offset(2, 1).Value = cel.Value
    End If
Next cel
End Sub

enter image description here

在此处输入图片说明

I added 1-6 in column D to show that it is ignoring the blanks

我在 D 列中添加了 1-6 以表明它忽略了空格