暂停VBA并在电子邮件中附加文件以供选择案例

时间:2015-10-26 17:31:43

标签: excel excel-vba vba

我试图暂停vba,直到用户保存excel附件(xlsx)?在下面的VB中,在打开工作簿时会提示用户选择,如果选择为是,则会出现另一个消息框,要求他们填写表单并保存。我试图暂停VB直到单击保存。但是,我目前收到很多编译错误。该附件文件也需要是电子邮件中的附件,但仅适用于该案例选择。该行在代码中以粗体显示,但截至目前尚无附件。此外,
我选择ActiveX component can't create object时会Set MyDoc = Documents.Add。谢谢你:)。

VB

Private Sub Workbook_Open()
Dim WS As Worksheet, Rng As Range, c As Range
Dim OutApp As Object, OutMail As Object
Dim Msg As String, Addr As String, FName As String, i As Long
Dim obj As Object
Dim MyDoc As Document
Dim MyFileCopy As String
Dim intAnswer As Integer

'define path
  MyFileCopy = "L:\NGS\HLA LAB\total quality management\QC & QA\DOSE reports\DOSE reporting form Attachment.xlsx"

'open sheet
  Sheets("Email").Activate
  intAnswer = MsgBox("Are there any issues to report", vbYesNoCancel)
  Select Case intAnswer
  Case vbYes
  Range("D2").Value = "x"
  MsgBox ("Please select an issue and save"), vbExclamation

 'create a separate sheet2 to mail out and pause VB
   Sheets(2).Copy
   Set wkb = ActiveWorkbook
   With wkb
  **Set MyDoc = Documents.Add
   MyDoc.SaveAs "MyFileCopy.xlsx"
   DoEvents
   Do
   Loop Until MyDoc.Saved
   .Close True
  End With

Case vbCancel
Application.SendKeys "%{F11}", True

Case Else
Range("C2").Value = "x"
End Select

'create connection, check condition, send email
 Set OutApp = CreateObject("Outlook.Application")
 Set WS = ThisWorkbook.Sheets("Email")
 With WS
 Set Rng = .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
 End With

 For Each c In Rng

Msg = "For " & WS.Cells(2, 2) & Chr(14) & Chr(14)
For i = 3 To 4
If LCase(WS.Cells(2, i)) = "x" Then
Msg = Msg & "   -" & WS.Cells(1, i) & Chr(14)
End If
Next

Set OutMail = OutApp.CreateItem(0)

With OutMail
    .To = c
    .CC = ""
    .BCC = ""
    .Subject = "Daily Operational Safety Briefing"
    .Body = Msg
    **If Range("D2").Value & Chr(14) = "x" Then .Attachments.Add MyFileCopy, 1**
    .Send
End With
Next c

Set OutMail = Nothing
Set OutApp = Nothing

'confirm message sent, clear sheet, and delete copy
 MsgBox "The data has been emailed sucessfully.", vbInformation
 Range("C2:D2").ClearContents
 Kill MyFileCopy


'Exit and do not save
 Application.Quit
 ThisWorkbook.Close SaveChanges:=False
 End Sub

1 个答案:

答案 0 :(得分:0)

我猜测" Form"实际上是Sheet2,他们必须填写一些东西或类似的东西。

您最好的选择是创建一个新的UserForm并设置属性" ShowModal"为假。在该表单中添加一个带有&#34的文本框;请选择一个问题并保存"然后您可以在表单上有一个名为" Save"将剩下的代码附加到它上面。

工作流程将是:

  1. 询问用户"是否有任何问题需要报告"
  2. 如果vbYes然后显示用户表单。
  3. 当用户完成他们所做的任何事情后,他们会点击" Save"在仍在上的表格
  4. 执行其余代码。
  5. 您可以选择使用Workbook_BeforeSave()事件(转到VBE中的ThisWorkbook,在编辑器的顶部选择"工作簿"形成第一个下拉菜单" BeforeSave&# 34;在第二个中)并将其余的代码放在那里。然后工作流程将是:

    1. 询问用户"是否有任何问题需要报告"
    2. 如果vbYes然后显示消息"请选择一个问题并保存"
    3. 用户关闭消息框并进行更新
    4. 用户点击"保存"
    5. workbook_BeforeSave()事件触发并执行其余代码。
    6. 你也可以将这些组合起来并且有#34;请选择一个问题并保存"消息框是一个ShowModal = False用户形态,它只是在他们做事情时保持活跃状态​​并且"保存"他们通常会这样做。