复制单元格并移动到另一个单元格(偏移量) – VBA BEGINNER

我有一个有很多空白和条目的专栏。 我想参赛(忽略空白),并把它们向右移动一次,两次,replace内容。 我有一种感觉,你会使用偏移function,但是我不知道如何写在VBA中。 我只使用偏移作为公式。 任何帮助,将不胜感激…

首先,您需要创build一个循环,移动范围的所有值。 有很多方法来创build循环,但是这里有一个例子:

 'find last row of range lastrow = ActiveSheet.UsedRange.Rows.Count 'Loops through the values from 2 to the last row of range For x=2 to lastrow Next x 

然后我build议循环遍历范围,并使用IF函数检查每个单元格值是否符合您的标准:

 'Checks for blank value in column A. If not blank If Cells(x, 1).Value <> "" then 'Do Something End IF 

现在为了复制新范围内的所有值,只需设置旧的和新的单元格的值相等:

 'Moves value from column A to column B and two cells down Cells(x+2, 2).Value = Cells(x, 1).Value 

总之,你的代码看起来像这样:

 Sub MoveValue () lastrow = ActiveSheet.UsedRange.Rows.Count For x=2 to lastrow If Cells(x, 1).Value <> "" then Cells(x+2, 2).Value = Cells(x, 1).Value End IF Next x End Sub 

这里是一个单线程:

 Range("A:A").SpecialCells(xlCellTypeConstants).Offset(2, 1).FormulaR1C1 = "=R[-2]C[-1]" '<--| change "A:A" to actual column index 

或者,如果您的“非空白”单元格来自单元格中的公式:

 Range("A:A").SpecialCells(xlCellTypeFormulas).Offset(2, 1).FormulaR1C1 = "=R[-2]C[-1]"