导出为CSV时关闭复制的工作表

时间:2011-09-23 19:43:03

标签: excel vba csv office-2010

我尝试将Excel电子表格的每个工作表保存为CSV文件。以下脚本完成了这项工作。行.Parent.Close savechanges:=False应该关闭创建的工作表,但是当取消注释时,脚本会在第一个工作表之后停止。如果我对该行进行评论,则会处理所有工作表。

Dim newWks As Worksheet
Dim wks As Worksheet

For Each wks In ActiveWorkbook.Worksheets
wks.Copy 'to a new workbook
Set newWks = ActiveSheet
With newWks
.SaveAs Filename:="C:\home\tmp\base\" & wks.Name & ".txt", FileFormat:=xlTextWindows
.Parent.Close savechanges:=False
End With
Next wks

MsgBox "done with: " & ActiveWorkbook.Name

1 个答案:

答案 0 :(得分:1)

您正在关闭活动工作簿。如果你想关闭新创建的对象,那么做这样的事情(测试它,它适用于我):

Dim newWkb As Workbook
Dim wks As Worksheet

For Each wks In ActiveWorkbook.Worksheets
  wks.Copy 'to a new workbook
  Set newWkb = ActiveWorkbook
  With newWkb
    .SaveAs Filename:="C:\home\tmp\base\" & wks.Name & ".txt", FileFormat:=xlTextWindows
    newWkb.Close savechanges:=False
  End With
Next wks

MsgBox "done with: " & ActiveWorkbook.Name