在最近添加的行上运行宏

时间:2017-08-09 01:22:08

标签: excel vba excel-vba

我正在使用宏根据已输入工作簿的数据生成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

1 个答案:

答案 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