我在以下目录中有一个.xlsx文件:
1
我可以将它指向此目录,但目录将根据它的年份而改变。
所以这个目录可能变成:
G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx
为了解决这个问题,我试图在路径中添加通配符,如下所示:
G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\9. 2018\2018 Planner.xlsx
我的工作簿无法打开。 请有人告诉我我哪里出错了吗?
子:
G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\" & "*." & " " & Year(Date) & "\"
功能:
'Find Planner
If Len(FindDepotMemo) Then
Set wb2 = Workbooks.Open(FindDepotMemo, ReadOnly:=True, UpdateLinks:=False)
End If
答案 0 :(得分:0)
尝试这种方法。代码循环通过文件夹名称1. 2020,1。2019,1。2018和当前年份,找到最低的,例如,1。2018存在。然后那一年它会查找最高的月份数字,放弃前一个月份的数字。例如,如果存在4. 2018,那就是使用原始代码查找文件名的路径。
Function FindDepotMemo() As String
Dim Pn As String ' Path name
Dim Fn As String ' Folder name
Dim Sp() As String ' Split string
Dim Arr() As String, Tmp As String
Dim FindFirstFile As String
Dim i As Integer
Dim n As Integer
For i = 2020 To Year(Date) Step -1
Pn = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\1. " & CStr(i) & "\"
If Len(Dir(Pn, vbDirectory)) Then Exit For
Next i
If i >= Year(Date) Then
Sp = Split(Pn, "\")
Arr = Sp
n = UBound(Sp) - 1
Fn = Sp(n)
For i = 2 To 12
Arr(n) = CStr(i) & Mid(Fn, 2)
Pn = Join(Arr, "\")
If Len(Dir(Pn, vbDirectory)) = 0 Then Exit For
Sp = Arr
Next i
FindFirstFile = Join(Sp, "\") & "*.xlsx"
While (FindFirstFile <> "")
If InStr(FindFirstFile, "Planner") > 0 Then
FindDepotMemo = Pn & FindFirstFile
Exit Do
End If
FindFirstFile = Dir
Wend
End If
End Function
如果未找到1. 2017或更高版本,则该函数返回空字符串。我无法测试缺少数据的代码。
答案 1 :(得分:0)
有很多方法,但我会用这种方法:
Function FindDepotMemo() As String
Dim oldPath, tempPath, newPath As String
Dim FindFirstFile As String
Dim addInt as Integer
' ASSUMING YOU ALREADY HAVE THIS PATH
' WE WILL USE THIS AS BASE PATH
' AND WE WILL INCREMENT THE NUMBER AND YEAR IN IT
oldPath = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017"
' EXTRACT 8. 2017 FROM oldPath
tempPath = Mid(oldPath, InStrRev(oldPath, "\") + 1)
' GET THE YEAR DIFFERENCE
addInt = Year(Date) - CInt(Split(tempPath, ".")(1))
' ADD THIS DIFFERENCE TO NUMBER AND YEAR
' AND NOW YOU HAVE CURRENT YEAR FOLDER
newTemp = Split(tempPath, ".")(0) + addInt & ". " & Split(tempPath, ".")(1) + addInt
FindFirstFile = Dir$(Path & "\" & "*.xlsx")
While (FindFirstFile <> "")
If InStr(FindFirstFile, "Test") > 0 Then
FindDepotMemo = Path & FindFirstFile
Exit Function
End If
FindFirstFile = Dir
Wend
End Function
我已添加评论以帮助您了解我在做什么。