简体   繁体   中英

Excel VBA - Import Macro that works but doesn't

I have the following Macro -

Sub Import_Data()

Dim rng As Range
Dim WB2 As Workbook
Dim FName As String
Dim c1 As Worksheet
Set c1 = Sheets("c")

    FName = Dir(Application.ActiveWorkbook.Path & "\*w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00") & ".xlsm")
    Set WB2 = Workbooks.Open(Filename:=FName)

    c1.Range("L2:O6").Value = WB2.Worksheets(2).Range("M2:P6").Value

    c1.Range("L14:O18").Value = WB2.Worksheets(2).Range("M14:P18").Value

WB2.Close

End Sub

When i run it i get the following error

在此处输入图片说明

So, the worksheet is there, i can open the worksheet but it won't accept it for some reason. Also, what's weird is that if i changed the file name of the worksheet it's looking for to "Fruit w32.xlsm", when i run the macro, the wildward will find "Fruit" but it will just say "Fruit" in the blank space in the picture

It worked perfectly fine but now it's having real issues and I don't understand why. Any Ideas?

EDIT: If i get rid of the Dir() part it works fine

The Dir function only returns the filename if found, so you have to specificy the path on opening.

FPath = Application.ActiveWorkbook.Path
FName = Dir(FPath & "\*w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00") & ".xlsm")
Set WB2 = Workbooks.Open(Filename:=FPath & "\" & FName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM