[英]Excel vba to copy and paste a cells from different worksheets to new worksheet
[英]Excel VBA Copy specific Column from different Worksheets
我目前正在使用VBA在Excel中開發監視工具,並且在復制數據時遇到了一些困難。
當前代碼:
Sub CopyID()
'Copies entire Row of IDs from "Sheet 2" to main Sheet "Main Sheet"
Dim lastCell As Long
LastCell = Cells(Rows.Count,'Sheet 2':M).End(xlUp).Row
'Missing here: Copy to Column 1 at Row 3!
Sheets("Sheet 2").Columns(M).Copy Destination:=Sheets("Main Sheet").Columns(1)
End Sub
應該執行的操作:將Sheet2_Column M的數據從第2行開始復制到Main Sheet Colum A在第3行發送
另外,我不知道這是否可行,請為目的地使用特定公式(格式為: =LEFT(Data,10)
)
對於對此的任何響應,我感到很高興,因為我想詳細了解這些“復制方法”的工作方式,並對有關這些方法的任何技巧和竅門感到高興。
編輯//復制部分應該像這樣工作
工作表2包含一個具有標頭單元格的X列和一個X單元格,其值具有相似的格式。
工作表2內容示例
這是工作表2中的一行。我只需要單元格內容的前10位。 是否可以將其作為類似於以下內容的公式
=Left(Sheet 2:M2,10)
所以它是這樣的:
“工作表2”單元格內容:將“ 1234567891_1_123X”復制為“ 1234567891”到“主工作表”
定義源和目標工作表。 范圍/列名稱也可以像"M"
這樣的字符串提交。
Sub CopyID()
'Copies entire Row of IDs from "Sheet 2" to main Sheet "Main Sheet"
Dim WsSource As Worksheet
Set WsSource = ThisWorkbook.Worksheets("Sheet 2")
Dim WsDestination As Worksheet
Set WsDestination = ThisWorkbook.Worksheets("Main Sheet")
Dim lastRow As Long
lastRow = WsSource.Cells(WsSource.Rows.Count, "M").End(xlUp).Row
'Missing here: Copy to Column 1 at Row 3!
WsSource.Range("M2:M" & lastRow).Copy Destination:=WsDestination.Range("A3")
End Sub
編輯:
要僅復制每個單元格的前10個字符,則需要對每個值進行處理:
Option Explicit
Public Sub CopyID()
'Copies entire Row of IDs from "Sheet 2" to main Sheet "Main Sheet"
Dim WsSource As Worksheet
Set WsSource = ThisWorkbook.Worksheets("Sheet 2")
Dim WsDestination As Worksheet
Set WsDestination = ThisWorkbook.Worksheets("Main Sheet")
Dim lastRow As Long
lastRow = WsSource.Cells(WsSource.Rows.Count, "M").End(xlUp).Row 'Find last row in column M
Dim ArrSource As Variant
ArrSource = WsSource.Range("M2:M" & lastRow).Value 'read column m values into array
Dim i As Long
For i = 1 To UBound(ArrSource) 'process each value in the array
ArrSource(i, 1) = Left$(ArrSource(i, 1), 10) 'keep only left 10 characters
Next i
WsDestination.Range("A3").Resize(UBound(ArrSource), 1).Value = ArrSource 'write array into destination
End Sub
注意.Resize(UBound(ArrSource), 1)
定義了目標,其大小與我們要插入的數組相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.