VBA |如何在Excel中将值从单元格复制到单元格 [英] VBA | How to Copy value from Cell to Cell in Excel

查看:201
本文介绍了VBA |如何在Excel中将值从单元格复制到单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将单元格值复制到另一个单元格,但是我想将值保留在变量中,以便我可以根据需要使用它。



以下是我试过的代码

  Private Sub CommandButton1_Click()
NumRows = Range(A1范围(A1)。End(xlDown))Rows.Count
对于x = 1到NumRows
a =单元格(x,1).Value.Copy
单元格(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)

对于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.

这篇关于VBA |如何在Excel中将值从单元格复制到单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆