简体   繁体   English

Excel宏将某些列从一个工作簿复制到另一个

[英]Excel Macro to copy certain columns from one workbook to another

This is my first attempt to write VBA code. 这是我第一次尝试编写VBA代码。 I am mimicking something I found on stackoverflow . 我正在模仿我在stackoverflow上发现的东西。

I want to copy certain columns (A, B and E) from one workbook to another and also change the font and color of certain Rows and edit the text in certain cells (replace a long phrase with the word "Group"). 我想将某些列(A,B和E)从一个工作簿复制到另一个工作簿,还希望更改某些行的字体和颜色,并在某些单元格中编辑文本(将长短语替换为“组”一词)。

This is the code I copied without change: 这是我复制的代码,没有更改:

Sub CopyColumnToWorkbook()
Dim sourceColumn As Range, targetColumn As Range

Set sourceColumn = Workbooks("Source").Worksheets("Sheet1").Columns("A")
Set targetColumn = Workbooks("Target").Worksheets("Sheet1").Columns("A")

sourceColumn.Copy Destination:=targetColumn
End Sub

I get a runtime error 9 and the line below is highlighted: 我收到一个运行时错误9,下面的行突出显示:

Set sourceColumn = Workbooks("Source").Worksheets("Sheet1").Columns("A")

I am attaching the Source and Target files below as I hope they would look like at the end of a successful run. 我在下面附加源文件和目标文件,希望它们在成功运行结束时看起来像。

Source File 源文件

Target File 目标文件

You reference a sheet that is not there. 您引用了不存在的工作表。 Change it to reference the first sheet in the workbook by using its index. 通过使用索引将其更改为引用工作簿中的第一张工作表。 You also did not include the extension to the file so it would fail on the workbook object as well. 您还没有包括该文件的扩展名,因此它也将在工作簿对象上失败。

Sub CopyColumnToWorkbook()
Dim sourceColumn As Range, targetColumn As Range

Set sourceColumn = Workbooks("Source.xlsm").Worksheets(1).Columns("A")
Set targetColumn = Workbooks("Target.xlsm").Worksheets(1).Columns("A")

sourceColumn.Copy Destination:=targetColumn
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM