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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13754791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:33:29  来源:igfitidea点击:

Excel Macro to copy certain columns from one workbook to another

excelexcel-vbavba

提问by Amatya

This is my first attempt to write VBA code. I am mimicking something I found on stackoverflow.

这是我第一次尝试编写 VBA 代码。我正在模仿我在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

目标文件

回答by Sorceri

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