我正在尝试重命名文件名并将其移动到另一个目录。同时,我正在尝试将重命名的文件存储在日志中。
下面是我的代码:
Sub MyRenamePDF()
Dim MyFolder As String
Dim MyFile As String
Dim i As Long
Dim MyOldFile As String
Dim MyNewFile As String
Dim dt As String
Dim FSO As Object
Dim rng As Range
Dim dat As Variant
dt = Format(Now(), "YYYY_MM_DD_HH_MM")
Set FSO = CreateObject("Scripting.Filesystemobject")
MyFolder = "D:\test\"
TargetFolder = "D:\output\"
MyFile = Dir(MyFolder & "\*.pdf")
Do While MyFile <> ""
MyOldFile = MyFolder & "\" & MyFile
MyNewFile = MyFolder & "\" & "0001" & "_" & dt & "_" & MyFile
Name MyOldFile As MyNewFile
With ThisWorkbook.Worksheets("Logs")
Set rng = Range("B2:B100")
For Each cell In rng
If cell.Value = "" Then
cell.Value = MyNewFile
End If
Next cell
End With
FSO.MoveFile MyNewFile, TargetFolder
MyFile = Dir
Loop
End Sub
我在此代码段中遇到了一个问题:
With ThisWorkbook.Worksheets("Logs")
Set rng = Range("B2:B100")
For Each cell In rng
If cell.Value = "" Then
cell.Value = MyNewFile
End If
Next cell
End With
其中值MyNewFile
被写入整个范围,而不是特定单元格,即B2
。
该怎么做?
答案 0 :(得分:2)
在将Exit For
写入B列的第一个空白单元格后,在If...End IF
中添加For
将退出MyNewFile
循环。
If cell.Value = "" Then
cell.Value = MyNewFile
Exit For
End If
但是使用Range.End
和xlUp
以及Offset
来查找列中第一个空白单元格的方法更加简洁。
With ThisWorkbook.Sheets("Logs")
.Cells(.Rows.Count, "B").End(xlUp).Offset(1).Value = MyNewFile
End With