我的VBA说我的子名称有错误

时间:2017-06-01 17:32:45

标签: excel vba excel-vba

我已将两个VBA合并为一个,但我在第一行收到错误,我将OpenLatestFile声明为公共子

我试图抓取最新文件并将该文件粘贴到名为LastQuerrySave的第二张表中

'Force the explicit delcaration of variables
Option Explicit

Public Sub OpenLatestFile()

'Declare the variables
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
Dim wb2 As Workbook
Dim wb1 As Workbook
Dim Sheet As Worksheet
Dim PasteStart As Range

Set wb1 = ActiveWorkbook
Set PasteStart = [LastQuerrySave!A1]
Sheets("LastQuerrySave").Select
    Cells.Select
    Selection.ClearContents

'Specify the path to the folder
MyPath = "M:\Users\Dan\Access\DiscontinueQuerry\DiscontinueQuerrySave\"

'Make sure that the path ends in a backslash
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

'Get the first Excel file from the folder
MyFile = Dir(MyPath & "*.xls", vbNormal)

'If no files were found, exit the sub
If Len(MyFile) = 0 Then
    MsgBox "No files were found...", vbExclamation
    Exit Sub
End If

'Loop through each Excel file in the folder
Do While Len(MyFile) > 0

    'Assign the date/time of the current file to a variable
    LMD = FileDateTime(MyPath & MyFile)

    'If the date/time of the current file is greater than the latest
    'recorded date, assign its filename and date/time to variables
    If LMD > LatestDate Then
        LatestFile = MyFile
        LatestDate = LMD
    End If

    'Get the next Excel file from the folder
    MyFile = Dir

Loop

'Open the latest file
 set wb2 =  Workbooks.Open MyPath & LatestFile

For Each Sheet In wb2.Sheets
    With Sheet.UsedRange
        .Copy PasteStart
        Set PasteStart = PasteStart.Offset(.Rows.Count)
    End With
Next Sheet

wb2.Close

End Sub

0 个答案:

没有答案