Я получаю ошибку 1004 при попытке использовать переменную LastRow для копирования и вставки данных - PullRequest
0 голосов
/ 08 января 2019

Заранее спасибо за помощь. У меня действительно вопрос об ошибке 1004, которую я получаю вокруг переменной LastRow, которую я пытаюсь использовать. Но я сделаю все возможное, чтобы объяснить все.

Код, который у меня есть:

-Первый просматривает определенную папку Windows, открывает последний обновленный файл в этой папке и открывает его.

-Код затем просматривает определенную папку Outlook и открывает большинство сообщений электронной почты в зависимости от того, есть ли в этом сообщении вложение.

-Вложение электронной почты извлекается, сохраняется в папке и открывается.

-В данный момент должно быть открыто 2 файла: один из электронного письма и файл, который был открыт из папки Windows.

-Что я пытаюсь сделать, это скопировать данные из одного файла в другой, и я пытаюсь использовать переменную LastRow для этого. В приведенном ниже коде все работает нормально, пока я не доберусь до строки, которая говорит ActiveSheet.Range("$A$1:$AB" & SixTimesLastRow).Copy

    Const olFolderInbox As Integer = 6
    '~~> Path for the attachment
    Const AttachmentPath As String = "C:\Users\DJ.Oliver\Documents\Test"
    Option Explicit
    Sub UpdateBusinessJustification()

    Dim oOlAp As Object, oOlns As Object, oOlInb As Object, CABLastRow As Long, 
    SixTimesLastRow As Long, objDoc As Object, objWord As Object, objSelection 
    As Object, nonProdCount As Integer, nonProdDT As Integer
    Dim oOlItm As Object, oOlAtch As Object, fname As String, sFound As String, 
    totalRowCount As Integer, wFound As String, wdRange As Word.Range, str As 
    String, nonProdCopyToWord As Long
    Dim wb As Workbook, uRng As Range, tbl As Table, ProdCount As Integer, 
    ProdDT As Integer, myDate As Date, tableCount As Integer, MyPath As String, 
    MyFile As String, LatestFile As String
    Dim LatestDate As Date, LMD As Date, CABPath As String, r As Range, x As 
    Variant, CopyCRRange As Range


    MyPath = "C:\Users\User\Documents\Reports\"
    CABPath = "C:\Users\User\Documents"


    MyFile = Dir(MyPath & "\CAB*.xlsx", vbNormal)

    If Len(MyFile) = 0 Then

        MsgBox "No files were found…", vbExclamation

        Exit Sub

    End If

    Do While Len(MyFile) > 0

        LMD = FileDateTime(MyPath & MyFile)

        If LMD > LatestDate Then

            LatestFile = MyFile

            LatestDate = LMD

        End If

        MyFile = Dir

    Loop

    'Open the latest CAB file

    Workbooks.Open MyPath & LatestFile

    Dim ws As Worksheet
    For Each ws In Worksheets
        If ws.AutoFilterMode Then
            ws.AutoFilterMode = False
        End If
    Next ws


    '~~> New File Name for the attachment
    Dim NewFileName As String
    NewFileName = "MorningOps " & Format(Date, "MM-DD-YYYY")
    '~~> Get Outlook instance
    Set oOlAp = GetObject(, "Outlook.application")
    Set oOlns = oOlAp.GetNamespace("MAPI")
    Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox).Folders("Daily CAB Reports")


    '~~> Check if there are any actual unread emails
    If oOlInb.Items.Restrict("[UnRead] = True").Count = 0 Then
        MsgBox "NO Unread Email In Inbox"
        Exit Sub
    End If

    '~~> Extract the attachment from the 1st unread email
    For Each oOlItm In oOlInb.Items.Restrict("[UnRead] = True")
        '~~> Check if the email actually has an attachment
        If oOlItm.Attachments.Count <> 0 Then
            For Each oOlAtch In oOlItm.Attachments
                '~~> Download the attachment
                oOlAtch.SaveAsFile NewFileName & oOlAtch.Filename
                Exit For
            Next
        Else
            MsgBox "The First item doesn't have an attachment"
        End If
        Exit For
    Next

    '~~> Mark 1st unread email as read
    For Each oOlItm In oOlInb.Items.Restrict("[UnRead] = True")
        oOlItm.UnRead = False
        DoEvents
        oOlItm.Save
        Exit For
        Next

    '--> Search for downloaded file and open without knowing exact filename
    sFound = Dir(CABPath & "\*Data Center CAB*.xlsx")
    If sFound <> "" Then
    Workbooks.Open Filename:=sFound
    End If

    'Set uRng = ActiveSheet.Range("A1:A2")

    '--> Set variable for last row in sheet containing data

    Workbooks(LatestFile).Activate
    CABLastRow = Sheets("CAB").Cells(Rows.Count, 1).End(xlUp).Row
    'Activate the latest CAB file and flear the contents
    'Workbooks(LatestFile).Activate
    Worksheets("CAB").Range("$A$1:$AB" & CABLastRow).ClearContents

    'Activate the 6x report and apply the filter to look for next week's changes
    Workbooks(sFound).Activate
    SixTimesLastRow = Sheets("Combined CAB Agenda").Cells(Rows.Count, 1).End(xlUp).Row
    ActiveSheet.Range("$A$1:$AB" & SixTimesLastRow).AutoFilter Field:=3, Criteria1:= _
        xlFilterNextWeek, Operator:=xlFilterDynamic

    'Copy next week changes from 6x daily report to CAB report
    ActiveSheet.Range("$A$1:$AB" & SixTimesLastRow).Copy


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