[英]How to create multiple Excel workbooks from a worksheet with VBA
I have a huge Excel report with many different server names and now I thought it might be possible to write a macro in VBA that creates a new excel file which is named after the server name.我有一个包含许多不同服务器名称的巨大 Excel 报告,现在我认为可以在 VBA 中编写一个宏来创建一个以服务器名称命名的新 Excel 文件。
For example my table has a column called "servername" and n rows which contain the name "Server1" and m rows which contain the name "Server2"例如,我的表有一个名为“servername”的列和包含名称“Server1”的 n 行和包含名称“Server2”的 m 行
Now I want the macro to create two files, Server1.xlsx and Server2.xlsx and both files contain every row which contains the servername.现在我希望宏创建两个文件,Server1.xlsx 和 Server2.xlsx,这两个文件都包含包含服务器名称的每一行。
Is this possible?这可能吗? If yes could you please help me I have never used VBA before and dont know how to start.
如果是的话,你能帮我吗?我以前从未使用过 VBA,也不知道如何开始。
You start by creating your two workbooks.您首先创建两个工作簿。 You now have three books.
你现在有三本书。 The original (which holds the program code) is referred to as ThisWorkbook, the other two are referred to by object variables.
原始(保存程序代码)被称为ThisWorkbook,另外两个被对象变量引用。 Then you start looping through each row in your existing page, and use an IF statement to take each row to either one or the other destination.
然后您开始遍历现有页面中的每一行,并使用 IF 语句将每一行带到一个或另一个目的地。 You stop when you reach a blank row.
当您到达空白行时停止。 Here's an example (note you will have to expand this yourself)
这是一个示例(请注意,您必须自己扩展)
Sub Example()
Dim wb as workbook 'declare an objvet variable
Set wb = workbooks.add() 'point it to a new instance of the workbook class
wb.saveas "File1.xlsx" 'save it as file1
dim source as Range 'pointer to original file
dim target1 as range 'pointer to destination
set Source = thisworkbook.worksheets(1),range("a1") 'point to a1 in source file
set target = wn.worksheets(1).range("a1")
Do 'start a loop
if source.text = "fred" then 'id cell holds this text then....
source.entirerow.copy target 'copy source to target
set target = target.offset(1,0) 'move target pointer down one row, no columns
end if
set source = source.offset(1,0) 'move source pointer
loop until source = "" 'stop at first blank cell
wb.save
It's entirely possible.这是完全可能的。 However, if you haven't written VBA before, you'll need to start there first.
但是,如果您以前没有编写过 VBA,则需要先从那里开始。
I recommend Bill Jelen's Excel VBA books .我推荐 Bill Jelen 的Excel VBA 书籍。 They're very informational and he is the top authority on all things Excel/VBA.
他们提供的信息非常丰富,他是 Excel/VBA 方面的最高权威。 If you don't want to pay, there is always Chip Pearson's site .
如果你不想付钱,总有Chip Pearson 的网站。
After you've developed a beginner's grasp of VBA, I'd recommend storing all of your metadata in an Excel Table
, loop through all rows in that table and create workbooks using the metadata in each row.在您掌握了 VBA 的初学者知识后,我建议您将所有元数据存储在 Excel
Table
,遍历该表中的所有行并使用每行中的元数据创建工作簿。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.