我看到几个问题询问如何使用 VBA 将单元格从一个工作簿移动到另一个工作簿或从一个工作表移动到另一个工作表,但我希望根据特定条件将信息从同一工作表中的一列移动到另一列。
我编写了以下代码,以便将包含单词“保存”的单元格从 A 列移至同一张表中的 I 列:
Sub Findandcut()
Dim rngA As Range
Dim cell As Range
Set rngA = Sheets("Jan BY").Range("A2:A1000")
For Each cell In rngA
If cell.Value = "save" Then
cell.EntireRow.Cut
Sheets("Jan BY").Range("I2").End(xlDown).Select
ActiveSheet.Paste
End If
Next cell
End Sub
但是,虽然这个宏在我运行时没有显示任何错误,但它似乎也没有做任何其他事情。没有选择、剪切或粘贴任何内容。我的代码哪里出错了?
最佳答案
move cells from column A if they contained the word "save" to column I in the same sheet
你的代码不会做这样的事情。
为了满足您的要求,您需要这样的东西:
Sub Findandcut()
Dim row As Long
For row = 2 To 1000
' Check if "save" appears in the value anywhere.
If Range("A" & row).Value Like "*save*" Then
' Copy the value and then blank the source.
Range("I" & row).Value = Range("A" & row).Value
Range("A" & row).Value = ""
End If
Next
End Sub
<小时/>
编辑
如果您想移动行的全部内容,使其从列 I
开始,只需替换相关的代码部分即可:
If Range("A" & row).Value Like "*save*" Then
' Shift the row so it starts at column I.
Dim i As Integer
For i = 1 To 8
Range("A" & row).Insert Shift:=xlToRight
Next
End If
关于用于根据特定单元格标准将单元格从一列移动到另一列的 VBA 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28349198/