vba 剪切、复制和粘贴excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25873529/
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-12 04:33:21  来源:igfitidea点击:

Cut, copy and paste excel

excelvbaexcel-vba

提问by Lancealott92

In VBA are you able to carry out a copy and paste straight after a cut and paste. I ask because If statement within a for loop that needs to cut a row of data and then copy the row directly underneath. When I run the code it performs that cut but never the copy. I looked into this online and the only thing I could come up with is clearing the clipboard. Sadly this not help :(.

在 VBA 中,您可以在剪切和粘贴后直接进行复制和粘贴。我问是因为for循环中的If语句需要剪切一行数据,然后直接复制下面的行。当我运行代码时,它执行那个剪切但从不执行复制。我在网上查看了这个,我唯一能想到的就是清除剪贴板。可悲的是,这无济于事:(。

Here is my code:

这是我的代码:

im r As Range
Dim i As Long, i2 As Long, i4 As Long
i = 2
i2 = 15
i3 = 70
i4 = 3
For Each r In ActiveSheet.UsedRange
v = r.Value
    If InStr(v, "ION") > 0 And InStr(v, "Dog") > 0 Then
        Range(Cells(r.Row, r.Column), Cells(r.Row, r.Column + 2)).Cut
        Range(Cells(i, 8), Cells(i, 10)).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Range(Cells(r.Row + 1, r.Column), Cells(r.Row + 1, r.Column + 2)).Copy
        Range(Cells(i4, 8), Cells(i4, 10)).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        i = i + 2
        i4 = i4 + 2

There is then more code using elseif's to search for other words but the code above is the code in question.

然后有更多代码使用 elseif 来搜索其他单词,但上面的代码是有问题的代码。

To reiterate, the cut/paste works. the copy/paste does not.

重申一下,剪切/粘贴有效。复制/粘贴没有。

Thanks.

谢谢。

回答by David Zemens

I'm not really able to replicate the problem you're having, but you could try changing these three lines:

我无法真正复制您遇到的问题,但您可以尝试更改以下三行:

Range(Cells(r.Row + 1, r.Column), Cells(r.Row + 1, r.Column + 2)).Copy
Range(Cells(i4, 8), Cells(i4, 10)).Select
ActiveSheet.Paste

To this:

对此:

Range(Cells(r.Row + 1, r.Column), Cells(r.Row + 1, r.Column + 2)).Copy _
    Range(Cells(i4, 8), Cells(i4, 10))

You can do the same thing with the .Cutmethod:, which would become:

你可以用.Cut方法做同样的事情:,它会变成:

Range(Cells(r.Row, r.Column), Cells(r.Row, r.Column + 2)).Cut _
    Range(Cells(i, 8), Cells(i, 10))

NB: It is rarely necessary to activate, Selector otherwise "click" the range objects that you need to work with. Here is a great explanation:

注意:很少需要激活Select或以其他方式“单击”您需要使用的范围对象。这是一个很好的解释:

How to avoid using Select in Excel VBA macros

如何避免在 Excel VBA 宏中使用 Select