导出为CSV而不会打开

时间:2018-03-19 17:17:36

标签: excel vb.net vba sharepoint

我正在使用Excel宏来检测两个工作表,并将它们写入当前SharePoint目录中的CSV格式。但是,在执行宏时,它会继续在同一工作簿中打开新创建的文件,并给出以下错误:

  

运行时错误'1004':

     

抱歉,我们找不到C:\ ProgramFiles(x86)\ Google \ Chrome \ Application ...

     

是否可以移动,重命名或删除?

我可以在不打开新文件的情况下执行“另存为”并避免给出错误吗?

要明确的是,它正好执行核心功能,因为新的CSV文件已正确写入Sharepoint文件夹,我只想避免错误消息。

宏代码如下:

Sub Export()
'
' Export Macro
' Export Rules and Privileges to 'Rules.csv' and  Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String

path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
    If ws.Name Like "Rules" Then
        ws.Activate
        ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
    End If
    If ws.Name Like "Privileges" Then
        ws.Activate
        ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
    End If
Next
    Range("B9").Select
    Application.Run "RulesWorkbook.xlsm!Export"
    Range("B4").Select
End Sub

1 个答案:

答案 0 :(得分:1)

感谢FreeMan提供解决错误消息的解决方案。虽然我没有弄清楚如何阻止Excel打开新生成的程序,但我能够通过在宏执行时关闭工作簿来支持这一点。宏的更新代码如下:

Sub Export()
'
' Export Macro
' Export SecurityRules and Privileges to 'Rules.csv' and 'Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String

path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
    If ws.Name Like "Rules" Then
    ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
    ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
End Sub