Excel VBA代码保存并关闭

时间:2016-02-16 11:41:44

标签: vba excel-vba excel

我想循环浏览2000个csv文件,将它们转换为xls,对电子表格进行更改。

在进入下一个工作簿之前,我无法弄清楚如何保存和关闭工作簿。

我在脚本结束时尝试了以下操作。

Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False

我收到轻微失真的保真信息。

完整代码

Sub batchconvertcsvxls()
Dim wb As Workbook
Dim strFile As String, strDir As String, strOut_Dir As String, myNewFileName As String

strDir = "C:\csv\" 'location of csv files
strOut_Dir = "C:\converted\" 'location of xls files
strFile = Dir(strDir & "*.csv")

Do While strFile <> ""

Set wb = Workbooks.Open(filename:=strDir & strFile, Local:=True)

    With wb
        .SaveAs strOut_Dir & Replace(wb.Name, ".csv", ".xls"), 56
        .Close True
    End With
Set wb = Nothing

Set wb = Workbooks.Open(filename:=strOut_Dir & Replace(strFile, ".csv", ".xls"))

Rows("1:1").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorDark2
    .TintAndShade = -0.249977111117893
    .PatternTintAndShade = 0
End With
Selection.RowHeight = 60
Selection.ColumnWidth = 30
With Selection
    .HorizontalAlignment = xlGeneral
    .VerticalAlignment = xlBottom
    .WrapText = True
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With
With Selection
    .HorizontalAlignment = xlGeneral
    .VerticalAlignment = xlTop
    .WrapText = True
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With
Columns("E:E").Select
With Selection
    .HorizontalAlignment = xlLeft
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With
Cells.Select
Selection.AutoFilter
Range("E2").Select
ActiveWindow.FreezePanes = True

For i = 1 To ActiveSheet.UsedRange.Columns.Count

    DataFound = False
    j = 2
    While DataFound = False And j <= ActiveSheet.UsedRange.Rows.Count
        If Cells(j, i).Value <> "" Then
            DataFound = True
        End If
        j = j + 1
    Wend
    If DataFound = False Then
        Columns(i).Hidden = True
    End If
Next

strFile = Dir

Application.ActiveWindow.Close SaveChanges:=True ActiveWorkbook.Close
SaveChanges:=False

Loop

End Sub

1 个答案:

答案 0 :(得分:0)

您可以尝试wb.Close SaveChanges:=False,因为您已将工作簿设置为wb,可能会在没有弹出消息框的情况下将其关闭。

你也可以尝试Application.DisplayAlerts = False(这是在你的代码的开头),它会阻止大多数类型的消息弹出(虽然有一些错误无法阻止(我没有列表但是&#34;内存不足&#34;是一个无法阻止的错误))。

我会更加正确地看待我这样做,如果我有更多的话,我会更新帖子