VBA For Loop正在输出错误的纸张(简单)

时间:2017-06-26 14:23:16

标签: excel vba excel-vba

执行时,此代码会创建一个新工作簿,然后将其保存到我的目录中。然后,我需要它填写专栏' A'带有时间戳的新工作簿,但我的循环是填充列' A'原始工作簿。 MsgBox确认Activesheet确实指向新的工作簿。我错过了什么?

'CREATING THE SHEET AND SAVING IT

Dim wb As Workbook
Set wb = Workbooks.Add(xlWBATWorksheet)
ActiveSheet.Name = "MySheet"
ActiveWorkbook.SaveAs "MyDirectory\MyWorkbook" & Space(1) & datetime

'FILLING COLUMN "A" WITH THE CURRENT DATE

With Workbooks("MyWorkbook" & Space(1) & datetime).Worksheets("MySheet")
    For i = 2 To Cells(Rows.Count, 2).End(xlUp).Row
        Cells(i, 1).Value = Format(CStr(Now), "mm_dd_yyyy")
    Next i
End With

1 个答案:

答案 0 :(得分:2)

使用With时,您必须在每个应该跟随该父级的对象前面指出.的链接:

Dim wb As Workbook
Set wb = Workbooks.Add(xlWBATWorksheet)
ActiveSheet.Name = "MySheet"
ActiveWorkbook.SaveAs "MyDirectory\MyWorkbook" & Space(1) & datetime

'FILLING COLUMN "A" WITH THE CURRENT DATE

With Workbooks("MyWorkbook" & Space(1) & datetime).Worksheets("MySheet")
    For i = 2 To .Cells(Rows.Count, 2).End(xlUp).Row
        .Cells(i, 1).Value = Format(CStr(Now), "mm_dd_yyyy")
    Next i
End With