Excel该进程无法访问该文件,因为它正由另一个进程使用

时间:2016-06-17 06:29:41

标签: excel-vba runtime-error vba excel

我创建了一个代码,该代码将以CSV格式保存Excel文件,并使用GMail作为附件通过电子邮件发送。

但是,我收到一个运行时错误,指出进程无法访问该文件,因为它正由另一个进程使用。

请参阅以下代码中我收到错误的部分代码。想知道如何解决这个问题。

非常感谢任何帮助。谢谢。

$profile_pic

1 个答案:

答案 0 :(得分:0)

不是最有效的方式,但它运作得非常好。将Excel工作簿保存为CSV后,我再次将其保存为具有不同文件名的CSV,然后附加第一个CSV文件。

'save workbook as csv file
ThisWorkbook.Sheets("Report").SaveAs Filename:= _
"report_" & userName & "_" & Format(Now, "mmddyy"), _
FileFormat:=xlCSVMSDOS, CreateBackup:=False

'save workbook as csv file with different filename
ThisWorkbook.Sheets("Report").SaveAs Filename:= _
"report_" & userName & "_" & Format(Now, "mmddyy") & "(copy)", _
FileFormat:=xlCSVMSDOS, CreateBackup:=False

'***********************************
'****send csv file as attachment****
'***********************************
Dim NewMail As Object
fName = "report_" & userName & "_" & yDate & ".csv"
myDir = myDir & "\"

Set NewMail = CreateObject("CDO.Message")

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusername") = gMail

NewMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendpassword") = sPassword

NewMail.Configuration.Fields.Update

'Set All Email Properties
With NewMail
  .Subject = "Report for " & userName & " " & yDate
  .From = gMail
  .To = "ddoctor@yahoo.com"
  .CC = ""
  .BCC = ""
  .AddAttachment myDir & Dir(myDir & fName)
End With

NewMail.send

MsgBox ("Mail has been Sent")

'Set the NewMail Variable to Nothing
Set NewMail = Nothing

ThisWorkbook.Close SaveChanges:=False

End If