[英]VBA | How to Copy value from Cell to Cell in Excel
我想將一個單元格值復制到另一個單元格,但是我想將該值保留在變量中,以便可以根據需要使用它。
以下是我嘗試的代碼-
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
我還建議顯式變量聲明。 它可以在您的選項中找到,也可以通過在任何子項或函數上方的“非常”頂部鍵入Option Explicit
來找到。 這將迫使您聲明變量。 我知道這感覺像是新手一樣的負擔,但是只需將一個錯字聲明為新變量即可改變主意。
如果只想將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
現在,如果要在代碼執行后使用變量a
,只需像下面這樣在sub外部聲明它:
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
現在,您需要測試變量a
是否為空,否則您將覆蓋它並達到目的。
像這樣的簡單檢查應該起作用:
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
希望能幫助到你。
首先,我建議您使用Developer功能區上的Record Macro工具。 確保啟用“使用相對引用”,並記錄一次您要執行的操作(將A1復制到B1)的鼠標單擊和擊鍵。 然后在VB中打開宏並進行修改。
這就是我使用這種方法時得到的結果,它似乎對我有用。 我希望它也對您有用。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.