2017-08-09 9 views
0

マクロを使用してブックに入力されたデータに基づいてOutlookテンプレートを生成しています。最近実行された行のマクロが追加されました

ブックには、100行のデータと7枚のシートがあります。

最新の行のデータでマクロを(ボタンをクリックして)実行し、テンプレートを生成する必要があります。

私の行には時刻データ(例13:37、次の行14:02など)が含まれていますので、最新の行を識別するのに適していると思います。

私はこのコードを使用しています。私はA203を使用して行を選択しています:G203

Sub NonConformanceGenerator() 

    ActiveSheet.Range("A203:G203").Select 

    Const HEADER_ROW As Long = 202 '<< the row with column headers 
    Const NUM_COLS As Long = 7 '<< how many columns of data 

    Const olMailItem = 0 
    Const olFolderInbox = 6 

    Dim ol As Object, fldr, ns, msg 
    Dim html As String, c As Range, colReq As Long, hdr As Range 
    Dim rw As Range 

    On Error Resume Next 
    Set ol = GetObject(, "outlook.application") 
    On Error GoTo 0 

    If ol Is Nothing Then 
     On Error Resume Next 
     Set ol = CreateObject("outlook.application") 
     Set ns = ol.GetNamespace("MAPI") 
     Set fldr = ns.GetDefaultFolder(olFolderInbox) 
     fldr.display 
     On Error GoTo 0 
    End If 

    If ol Is Nothing Then 
     MsgBox "Couldn't start Outlook to compose mail!", vbExclamation 
     Exit Sub 
    End If 

    Set msg = ol.CreateItem(olMailItem) 

    Set rw = Selection.Cells(1).EntireRow 

    msg.Subject = "" 

    html = "<style type='text/css'>" 
    html = html & "body, p {font:11pt calibri;padding:40px;}" 
    html = html & "table {border-collapse:collapse}" 
    html = html & "td {border:1px solid #000;padding:8px;}" 
    html = html & "</style>" 

    html = html & "<p>Hello,</p>" 
    html = html & "<table>" 

For Each c In rw.Cells(1).Resize(1, NUM_COLS).Cells 

    If c.Column <> 0 Then '<<< This removes the 4th column if you type number 4 after the <> symbols 

     Set hdr = rw.Parent.Cells(HEADER_ROW, c.Column) '<< get the header text for this cell 

     html = html & "<tr><td style='background-color:#FFF;width:200px;'>" & _ 
      hdr.Value & _ 
      "</td><td style='width:400px;'>" & Trim(c.Value) & "</td></tr>" 

     End If 'we want this cell 

    Next c 

    html = html & "</table>" 

    msg.HTMLBody = html 
    msg.display 

    ActiveSheet.Range("A15").Select 

End Sub 
+0

あなたは、コード内の範囲を選択する必要はありません - ちょうどマウス(またはキーボード)を使用して、行の任意のセルを選択し、マクロを実行する(多分それをトリガするためにシート上のボタンを追加します) - それは自動的に "アクティブな"行をピックアップします。 –

答えて

1

は、スプレッドシートの下部に常に最新の行ですか?その場合は、たとえばCells(Rows.Count, "A").End(xlUp).Rowを使用して、列「A」のデータを含む最後の行を戻すことができます。

あなたの例で使用するために、このようなことを行うことができます。

With ActiveSheet 
    .Range("A" & .Cells(.Rows.Count, "A").End(xlUp).Row).Resize(1, 7).Select 
End With 
関連する問題