我已經花了一整個上午的時間,但無法使其正常作業。創建了一個簡單的 Excel 用戶表單,要求輸入檔案名。如果該檔案存在于我希望它打開的目錄中。如果它不存在,我想打開一個“模板”檔案。我的不存在正常作業,但是無法使“確實存在”部分正常作業。請幫忙。
Private Sub CmdEnter_Click()
Dim Path As String
Dim File As String
Path = Range("Search!B1")
File = TxtOrder.Value
'If File exists then open.
If Dir(Path & File & ".xlsm") = Path & File & ".xlsm" Then
Workbooks.Open FileName:=Path & File & ".xlsm"
'If File does not exist then open.
ElseIf Dir(Path & File & ".xlsm") = Error Then
Workbooks.Open FileName:=Path & "QCSFormTrial.xlsm"
End If
'Close Dialog and Close Workbook
Workbooks("QCSLaunch.XLSM").Close SaveChanges:=False
結束子
uj5u.com熱心網友回復:
請嘗試這種方式:
Private Sub CmdEnter_Click()
Dim Path As String, File As String, wb As Workbook
Path = Range("Search!B1")
File = TxtOrder.value
'If File exists then open.
If dir(Path & File & ".xlsm") <> "" Then
Set wb = Workbooks.Open(Path & File & ".xlsm")
Else 'else, open the other one:
Set wb = Workbooks.Open(Path & "QCSFormTrial.xlsm")
End If
Stop 'check if the workbook has been open and press F5 to let code finishing
wb.Close SaveChanges:=False
End Sub
uj5u.com熱心網友回復:
問題是Dir(Path & File & ".xlsm") = Path & File & ".xlsm"基本上是說我命名的檔案夾路徑是否等于我命名的檔案夾路徑。該路徑實際上并不以打開它的方式指向實際檔案夾。
試試這個:https : //exceloffthegrid.com/vba-code-loop-files-folder-sub-folders/
Sub LoopAllFilesInAFolder()
'Loop through all files in a folder
Dim fileName As Variant
fileName = Dir("C:\Users\marks\Documents\")
While fileName <> ""
'Insert the actions to be performed on each file
'This example will print the file name to the immediate window
Debug.Print fileName
'Set the fileName to the next file
fileName = Dir
Wend
End Sub
或者,您可以洗掉If Then并直接打開檔案。如果檔案存在,它將打開,如果不存在,它將打開error。您可以使用error handling然后繼續。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/366924.html
上一篇:按具有數值(和標題)的列對Python中的CSV進行排序
下一篇:選擇圖表時呼叫宏
