[英]copy-paste columns on excel VBA
幾天來一直試圖在excel VBA上復制粘貼列,無論如何,代碼都無法正常工作
Sub CopyRangeofCellsanotherone()
Dim x As Workbook
Dim y As Workbook
Dim LastRow As Long
Dim LastRowToCopy As Long
Set x = Workbooks.Open("C:\trabalho da DELL\source.xlsx")
Set y = Workbooks.Open("C:\trabalho da DELL\destination.xlsx")
LastRowToCopy = x.Sheets("sourcesheet").Cells(x.Sheets("sourcesheet").Rows.Count, "A").End(xlUp).Row
x.Sheets("sourcesheet").Range("A" & LastRowToCopy).Copy 'copy from A1 to lastrow
LastRow = y.Sheets("destsheet").Cells(y.Sheets("destsheet").Rows.Count, "A").End(xlUp).Row 'find the last row
y.Sheets("destsheet").Range("A" & LastRow).PasteSpecial 'paste on the lastrow of destination + 1 (so next empty row)
x.Close
End Sub
我認為代碼大部分是不言自明的(或者至少是我打算做的),但是它不起作用! 如何將內容從A列-源工作表復制到A列-目標工作表? 然后,我該如何將其應用於一組列? (例如,從A到G)。 我的VBA不足5個小時,因此對於您中的某些人來說看起來真的很簡單...編輯:忘了提及它在LastRowToCopy行上給了我運行時錯誤91。
試試下面的代碼。
關於您所寫內容的注釋:
擴展此范圍以完全引用一個范圍,而不僅僅是一個單元格
sourceSheet.Range("A1:A" & sourceLastRow)
在此處添加+1以粘貼到下一個可用行
destSheet.Range("A" & destLastRow + 1)
為工作表本身設置變量,使代碼更易讀
Set sourceSheet = sourceBk.Sheets("sourcesheet")
在lastRow變量中包含更多描述,以便您知道正在引用哪個工作簿和工作表
sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
當然,在頂部有Option Explicit
可以檢查變量聲明。
完整代碼:
Option Explicit
Sub CopyRangeofCellsanotherone()
Dim sourceBk As Workbook
Dim destBK As Workbook
Dim sourceLastRow As Long
Dim destLastRow As Long
Dim sourceSheet As Worksheet
Dim destSheet As Worksheet
Set sourceBk = Workbooks.Open("C:\trabalho da DELL\source.xlsx")
Set destBK = Workbooks.Open("C:\trabalho da DELL\destination.xlsx")
Set sourceSheet = sourceBk.Sheets("sourcesheet")
Set destSheet = destBK.Sheets("destsheet")
sourceLastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row
destLastRow = destSheet.Cells(destSheet.Rows.Count, "A").End(xlUp).Row 'find the last row
sourceSheet.Range("A1:A" & sourceLastRow).Copy 'copy from A1 to lastrow
destSheet.Range("A" & destLastRow + 1).PasteSpecial 'paste on the lastrow of destination + 1 (so next empty row)
sourceBk.Close
End Sub
擴展復印范圍:
有多種方法可以將其擴展到一系列列(您將需要對此進行進一步說明)。
例如,如果您事先知道最后一列,例如“ C”,則可以如下修改sourceSheet范圍的行:
sourceSheet.Range("A1:C" & sourceLastRow)
如果您不知道,您可以找到最后一欄,例如根據Ron De Bruin
sourceLastCol =sourceSheet.Cells(1,sourceSheet.Columns.Count).End(xlToLeft).Column
復制源范圍的語法將變為
sourceSheet.Range(sourceSheet.Cells(1, 1), sourceSheet.Cells(sourceLastRow, sourceLastCol)).Copy
Sub foo2()
Dim x As Workbook
Dim y As Workbook
Set x = Workbooks.Open("C:\trabalho da DELL\source.xlsx")
Set y = Workbooks.Open("C:\trabalho da DELL\destination.xlsx")
y.Sheets("destsheet").Range("A:A").Value = x.Sheets("sourcesheet").Range("A:A").Value
x.Close
End Sub
檢查以上代碼是否成功復制了列A。
如果是這樣,則重復該行
y.Sheets(“ destsheet”)。Range(“ A:A”)。Value = x.Sheets(“ sourcesheet”)。Range(“ A:A”)。Value
用其他列替換A列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.