Как использовать «для цикла» в почте с помощью Excel VBA? - PullRequest
0 голосов
/ 22 мая 2019

Мне нужно отправить список пользователей, работающих в разных проектах. но чтобы получить эти данные, мне нужно сначала отфильтровать проект данных по проекту, а затем записать имя проекта и скопировать соответствующие данные в mail-body и т. д.

Работая над кодом для отправки почты с использованием vba, я застрял в цикле строки .htmlbody, чтобы она добавлялась ко всем данным проекта один под другим. При выполнении кода я получаю сообщение об ошибке «требуется объект».

Я пытался установить "tabl" до и после почтового кода, но ни один из них не помог

Sub Mail_Selection_Range_Outlook_Body()

Dim Rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim xCell As Range
Dim tabl As Range
Dim xAddress As String


'Set rng = Nothing
' Only send the visible cells in the selection.
'Set rng = Sheets("Sheet1").Range("A1", Range("A" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeVisible)
'Set rng = Sheets("Sheet1").Range("B1:F5").SpecialCells(xlCellTypeVisible)

'If rng Is Nothing Then
'MsgBox "The selection is not a range or the sheet is protected. " & _
       vbNewLine & "Please correct and try again.", vbOKOnly
'Exit Sub
'End If

With Application
  .EnableEvents = False
  .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

Set tabl = Sheets("Sheet2").Range("A1:A10")
With OutMail
  .Display
  .to = "ME@ME.COM"
  .CC = ""
  .BCC = ""
  .Subject = "This is the Subject line"
  '.body = "Here is the email body"
  'Call append
  .htmlbody = "Hi All"
  For Each xCell In tabl
      If xCell.Value Like "GBL?*" Then
  'Here the error pops out
          Set Rng = Nothing
          .htmlbody = .htmlbody + xCell.Value & "Projects" & RangetoHTML(Range("A1", ActiveSheet.Cells.SpecialCells(xlCellTypeVisible)))
      End If
  Next
  .Display
End With
On Error GoTo 0

With Application
  .EnableEvents = True
  .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(Rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook



ActiveWorkbook.Sheets(1).Activate


ActiveSheet.Range("A1", ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell)).AutoFilter Field:=2, Criteria1:=xCell.Value, Operator:=None

Set Rng = Range("A1", ActiveSheet.Cells.SpecialCells(xlCellTypeVisible))

TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
Rng.Copy
Set TempWB = Workbooks.add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , True, False
    .Cells(1).PasteSpecial xlPasteFormats, , True, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

Теперь, как мне зациклить часть кода .htmlbody?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...