且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-29 09:19:56

不需要使用 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)

对于x = 1到NumRows
a(x)=单元格(x,1).Value
单元格(X,2).Value = a(x)
下一个x
pre>

我还建议使用显式变量声明。可以在您的选项中找到,或者在任何子页面或函数上方的VERY顶部键入 Option Explicit 。这将强制您声明变量。我知道这感觉像是一个新手的负担,但是只需要一个打字错误就被声明为一个新的变量来改变主意。


I want to copy a cell value to another cell, but I want to retain the value in a variable so I can use it as per requirement.

Following is the code i tried-

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

No need to use the Range.Copy method. Try this:

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

If you want to retain ALL of the values, you will need to use an array:

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

I also recommend explicit variable declaration. It can be found in your options or by typing Option Explicitat the VERY top, above any subs or functions. This will force you to declare your variables. I know it feels like a burden as a newbee, but it only takes one typo getting declared as a new variable to change your mind.