宏正在更改选项卡名称

时间:2014-06-23 09:56:31

标签: excel vba excel-vba

我在文件夹中有excel文件。我想将每个excel文件(只有sheet1)转换为csv文件。我通过使用下面的宏来完成这个。我无法确定代码更改选项卡名称中的哪一行带有文件名。我不想改变标签名称。

Option Explicit
Sub SaveasCSV()
Dim bookList As Workbook
Dim createObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set createObj = CreateObject("Scripting.FileSystemObject")
ChDir "C:\Users\puttaraju.d\Desktop\Phase1"
Set dirObj = createObj.GetFolder("C:\Users\puttaraju.d\Desktop\Phase1")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
ActiveWorkbook.SaveAs FileFormat:=xlCSV, CreateBackup:=False 
bookList.Close
Next
End Sub

对于每个文件,弹出打开以询问您是否要保存文件中的更改。我不想改变当前的文件。我怎样才能添加代码行来做到这一点。

1 个答案:

答案 0 :(得分:2)

这是一行:

ActiveWorkbook.SaveAs FileFormat:=xlCSV

尝试手动将工作簿另存为CSV。您将看到它更改选项卡名称以匹配文件名(没有.csv扩展名)。

您可以使用SaveCopyAs保存您的worbook的临时副本,然后打开该副本,并将其另存为CSV(并将其关闭并删除)。

这是我的一个旧程序,使用不同的方法做类似的事情。它将工作表保存为文本:将工作表复制到另一个临时工作簿,然后将该工作簿另存为文本。适应您的需求。

Sub SaveSheetAsTextFile(sourceSheet As Worksheet, textFilePath As String)
    Dim oldScreenUpdating As Boolean
    Dim thisbook As Workbook
    Dim tempbook As Workbook

    oldScreenUpdating = Application.ScreenUpdating
    Application.ScreenUpdating = False

    ' Copy sheet to a new temp workbook
    Set thisbook = ActiveWorkbook
    Set tempbook = Workbooks.Add
    thisbook.Activate
    sourceSheet.Cells.Copy tempbook.ActiveSheet.Range("A1")

    ' Save as text file
    tempbook.ActiveSheet.SaveAs filename:=textFilePath, _
                                FileFormat:=xlTextPrinter
    'FileFormat:=xlTextWindows  ' this puts text cells in "quotes"!

    tempbook.Close SaveChanges:=False
    Application.ScreenUpdating = oldScreenUpdating
End Sub

使用示例:

SaveSheetAsTextFile Sheet1, "C:\myfile.txt"