从工作表1中的按钮调用宏,并在工作表2中写入一些数据

时间:2018-09-12 19:50:05

标签: vba excel-vba

我试图通过使用工作表Homepage中的按钮并希望其将数据写入工作表Logs中来调用以下代码。但是,当我这样做时,数据将被写入调用宏的同一张纸中。

下面是我的代码:

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 input_file As String
Dim output_file As String
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
    output_file = FSO.GetFileName(MyNewFile)
    With ThisWorkbook.Worksheets("Logs")
        Cells(.Rows.Count, "B").End(xlUp).Offset(1).Value = output_file
        Cells(.Rows.Count, "A").End(xlUp).Offset(1).Value = MyFile
    End With
    FSO.MoveFile MyNewFile, TargetFolder
    MyFile = Dir
 Loop
End Sub

这里可能出了什么问题?

2 个答案:

答案 0 :(得分:2)

.Cells(.Rows.Count, "B")...前面添加句点Cells(.Rows.Count, "A")...

按原样,暗含ActiveSheet-您实际上并没有使用With...End With块。

有关更多详细信息,请参见Using With Statements

答案 1 :(得分:1)

我认为您只需要添加一个“。”在“ With”语句中的单元格前面:

With ThisWorkbook.Worksheets("Logs")
    .Cells(.Rows.Count, "B").End(xlUp).Offset(1).Value = output_file
    .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Value = MyFile
End With