VBA | 如何在Excel中将值从单元格复制到单元格

我想复制一个单元格值到另一个单元格,但我想保留在一个variables的值,所以我可以按需要使用它。

以下是我试过的代码 –

Private Sub CommandButton1_Click() NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count For x = 1 To NumRows a= Cells(x, 1).Value.Copy Cells(x, 2).Value= a.PasteSpecial Next End Sub 

不需要使用Range.Copy方法。 尝试这个:

 Dim a As Variant a = Cells(x, 1).Value Cells(x, 2).Value = a 

如果你想保留所有的值,你将需要使用一个数组:

 Dim x As Long Dim NumRows As Long NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count ReDim a(1 to NumRows) For x = 1 To NumRows a(x) = Cells(x,1).Value Cells(X,2).Value = a(x) Next x 

我也build议显式variables声明。 它可以在您的选项中find,也可以在任何子项或函数上面的VERY top上键入Option Explicit 。 这将迫使你声明你的variables。 我知道这感觉就像是一个新手一样的负担,但是只要把一个错误作为一个新的variables来改变你的想法。

如果你只是想将Range值传递给数组,则不需要循环。
尝试这样的事情:

 Dim a With Sheets("YourSheetName") a = Application.Transpose(.Range("A1", .Range("A" & _ .Rows.Count).End(xlUp).Address)) End With '~~> check your array For i = Lbound(a) To Ubound(a) Debug.Print a(i) '~~> rest of your code here to do what you like. Next 

现在,如果你想在代码执行后使用你的variables,只需要在这个子外面声明它:

 Dim a As Variant '~~> you can also use Public a As Variant Sub Something() '~~> put similar code above here and the rest of your code End Sub 

现在,如果variablesa是空的,你需要进行一个testing,否则你会覆盖它,并打败你的目的。
像这样的一个简单的检查应该工作:

 If IsEmpty(a) Then '~~> or IsArray if you're sure you'll always have a as array '~~> populate a '~~> proceed with what you want to do with a Else '~~> proceed with what you want to do with a End If 

希望能帮助到你。

首先,我build议您使用开发人员function区上的“loggingmacros”function。 确保设置“使用相对引用”,然后logging鼠标单击和按键操作(将A1复制到B1)。 然后在VB中打开macros并修改它。

这是我使用这种方法时得到的,似乎对我有用。 我希望它也适用于你。

 Sub Macro1() Dim NumRows As Integer NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count Range("A1").Activate For i = 1 To NumRows ActiveCell.Select Selection.Copy ActiveCell.Offset(0, 1).Range("A1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False ActiveCell.Offset(1, -1).Activate Next End Sub