Excel 2003 VBA:将工作表移动到变量引用的新工作簿中
我有一个函数,旨在运行数据透视表的 ShowPages()
命令,然后将每个工作表保存到单独的文件中。
我希望我可以这样做:
Sub Split()
ThisWorkbook.Sheets("Data").PivotTables("Data").ShowPages PageField:="Codename"
Dim newWb As Workbook
For Each s In ThisWorkbook.Sheets
If s.Name <> "Data" Then
Set newWb = s.Move #This is the line I'm trying to work out
newWb.SaveAs Filename:="C:\Export\" + s.Name + ".xls"
newWb.Close
End If
Next s
End Sub
不幸的是,这遇到了一堆与没有创建对象等相关的问题(可以理解)。做到这一点最明智的方法是什么?
I have a function that is meant to run the ShowPages()
command of a PivotTable and then save each sheet to a separate file.
Here's how I wish I could do it:
Sub Split()
ThisWorkbook.Sheets("Data").PivotTables("Data").ShowPages PageField:="Codename"
Dim newWb As Workbook
For Each s In ThisWorkbook.Sheets
If s.Name <> "Data" Then
Set newWb = s.Move #This is the line I'm trying to work out
newWb.SaveAs Filename:="C:\Export\" + s.Name + ".xls"
newWb.Close
End If
Next s
End Sub
Unfortunately, this is running into a bunch of issues to do with not having created objects and suchlike (understandably). What is the most sensible way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然这已经很旧了,并且士兵接受的答案非常好,只是想添加一件事。 Excel VBA Sheets.Copy 和 Sheets.Move 方法有一个非常好的功能。它们采用两个可选参数“之前”或“之后”之一来定位移动/复制的工作表。 Excel 文档指出:
因此,这几乎令人惊讶,但您可以只说:
在接受的答案中,代替:
士兵的其余代码可以通过这种简化很好地工作。
Although this is old, and the accepted answer by soldieraman is very nice, just wanted to add one thing. The Excel VBA Sheets.Copy and Sheets.Move methods have a very nice feature. They take either of two optional arguments, "Before" or "After", to position a moved/copied sheet. The Excel documentation notes that:
So, it is almost surprising, but you can just say:
in the accepted answer, in place of:
The rest of soldieraman's code would work fine with this simplification.