我的要求是
1)打开现有的Excel工作簿
2)识别下一个空行并在该行中输入时间戳
3)保存并关闭Excel工作簿
为实现这一点,我使用了以下代码:
Sub UpdateReport()
Dim directory As String, fileName As String
Dim FirstBlankCell As Range
Application.ScreenUpdating = False
directory = "C:\Users\Desktop\Excel_sheets\"
fileName = Dir(directory & "Reports.xls")
Set wbr = Workbooks.Open(directory & fileName, ReadOnly:=False)
Set FirstBlankCell = Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
FirstBlankCell.Activate
myTimeStamp = Format(Now, "yyyy-mm-dd_hhmmss")
FirstBlankCell.Value = myTimeStamp
wbr.Saved = True
'wbr.Close True
End Sub
我面临的问题是此代码仅在表单打开时才更新表单,并且还会覆盖表单。 我希望在下一个空单元格中设置时间戳,而不是在不保持excel打开的情况下写入旧单元格
答案 0 :(得分:0)
以下代码应符合您的要求:
Sub UpdateReport()
Dim directory As String, fileName As String
Dim FirstBlankCell As Range
directory = "C:\Users\raj.kamal\Documents"
fileName = "stack1.xlsx"
Application.ScreenUpdating = False
Set ExcelAppl = CreateObject("Excel.Application")
Set wb = Application.Workbooks.Open(directory & "/" & fileName, ReadOnly:=False)
wb.Activate
Set ws = wb.Worksheets(1)
Set FirstBlankCell = ws.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
myTimeStamp = Format(Now, "yyyy-mm-dd_hhmmss")
ws.Activate
FirstBlankCell = myTimeStamp
wb.Save
wb.Close
ExcelAppl.Quit
Set wb = Nothing
Set ExcelAppl = Nothing
End Sub