[英]How can I delete a file based on cell value?
我在刪除基於單元格值的文件時遇到問題。 我在下面的Kill命令中收到一條錯誤消息:
Kill path & r.Offset(1, -4) & "\" & r.Offset(1, -3)
有任何想法嗎?
Sub INACTIVE_files()
Const path = "C:\Users\NikolouzosD\AppData\Local\Temp\vbakillfunction\"
Dim r As Range
Dim x As Integer
Set r = Cells(1, 5)
Do Until r = ""
If UCase(r.value) = "INACTIVE" Then
Kill path & r.Offset(1, -4) & "\" & r.Offset(1, -3)
End If
Set r = r.Offset(1, 0)
Loop
End Sub
該代碼從單元格E1開始,並在同一列中查找INACTIVE文件,直到沒有其他文件可查找為止。 然后,它檢查文件夾名稱(A列),將其與多維數據集(B列)合並,然后將它們都放在路徑中:
path = "C:\Users\NikolouzosD\AppData\Local\Temp\vbakillfunction\"
因此,例如:對於無效的單元格E2,路徑應為:
C:\Users\NikolouzosD\AppData\Local\Temp\vbakillfunction\WPO 17 02 04 3MMT All Periods\BG023104.txt
然后,它從相應的文件夾中刪除INACTIVE文件(多維數據集)。
將路徑用雙引號引起來,以避免文件名和文件夾中的空格出現問題。
更好的是將路徑放在字符串變量中,以便您輕松調試它
在循環之外:
Dim strPath As String
在您的if塊內:
strPath = """" & path & r.Offset(1,-4) & "\" & r.Offset(1,-3) & """"
Debug.Print strPath ' Ctrl-G to view results
Kill strPath
編輯-刪除前添加文件檢查
在Tools | References
Tools | References
添加對Windows腳本托管的引用
然后在子代碼頂部添加
Dim fso as New FileSystemObject
用檢查是否存在來替換您的Kill命令
If fso.FileExists(strPath) Then
Kill strPath
Else
Msgbox "File Doesn't Exist: " & strPath
End If
已更新以繼續到下一個文件
將循環更改為:
Do Until r = ""
If UCase(r.value) = "INACTIVE" AND fso.FileExists(strPath) Then
Kill strPath
End If
Set r = r.Offset(1, 0)
Loop
有用! 我已經注釋掉了用於檢查文件是否存在的部分代碼。
Sub delete_INACTIVE_files()
Const path = "C:\Users\Dn\AppData\Local\Temp\vbakillfunction\"
Dim r As Range
Set r = Cells(1, 5)
Do Until r = ""
If UCase(r.Value) = "INACTIVE" Then
If Dir(path & r.Offset(0, -4) & "\" & r.Offset(0, -3) & ".txt") <> "" Then 'Does the file exist?
'MsgBox "file" & path & r.Offset(0, -4) & "\" & r.Offset(0, -3) & ".txt" & " exists"
Kill path & r.Offset(0, -4) & "\" & r.Offset(0, -3) & ".txt"
'Else
'MsgBox "file" & path & r.Offset(0, -4) & "\" & r.Offset(0, -3) & ".txt" & " not here"
End If
End If
Set r = r.Offset(1, 0)
Loop
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.