我需要将多个不相邻的列复制到另一个名为Extract.xlsx的Excel工作簿中
'Path to destination
MyPath = "C:\Users\valerie\Desktop\Template\Extract.xlsx"
'Range Selection
Range("A:A, G:G, J:J, K:K, M:M").Select 'This is what I initially recorded from excel macro, but realised that an error popped up saying "That command cannot be used on multiple selections."
'Open Destination Workbook, was testing it out separately so I know this part onwards works
Workbooks.Open(MyPath)
Set wb = Workbooks.Open(MyPath)
Set ws1 = wb.Worksheets("Sheet1")
ws1.Activate
Range("A1").Select
Activesheet.Paste
我尝试查找一些示例,但我要么听不懂他们在说什么,要么弹出相同的错误消息
答案 0 :(得分:1)
由于您不使用PasteSpecial,因此可以将数据复制到一行中。我只添加变量以提高可读性和可用性:
dim Rng_A as Range, Rng_B as Range, wb as Workbook, ws1 as Worksheet
MyPath = "C:\Users\valerie\Desktop\Template\Extract.xlsx"
Workbooks.Open(MyPath)
Set wb = Workbooks.Open(MyPath)
Set ws1 = wb.Worksheets("Sheet1")
' ThisWorkbook - for a book where code is executed
set Rng_A = ThisWorkbook.Worksheets("Your_Sheet_Name").Range("A:A, G:G, J:J, K:K, M:M")
set Rng_B = ws1.Range("A1")
Rng_A.Copy Rng_B
由于您正在使用多个工作表/工作簿,因此我建议您注意代码的视场,并尽量避免在没有与之相关的对象的情况下使用Range(...)。