我正在尝试自己学习VBA,并且我试图接收电子邮件的正文,将其解析出来并仅将数组中的元素保存到excel文件中。我这样做,我的问题是我似乎无法更新文件中已有的内容。它只是用新的电子邮件信息重写并保存。 我的问题是:我的代码需要能够继续写入我的excel文件,而不必删除已存在的内容。
Sub FMK(Item As Outlook.MailItem)
Const PathName = "C:\Users\carter\Desktop\fmk.xlsx"
Dim arrLines As Variant, _
varLines As Variant, _
RowNext As Integer, _
xlApp As Excel.Application, _
ExcelWkBk As Excel.Workbook, _
excWkb As Object, _
excWks As Object, _
temp As String
arrLines = Split(Item.Body, vbCrLf)
Set xlApp = Application.CreateObject("Excel.Application")
Set excWkb = xlApp.Workbooks.Add()
Set excWks = excWkb.ActiveSheet
temp = Trim(arrLines(32))
RowNext = 1
With excWks
excWks.Cells(RowNext, 1) = temp
End With
RowNext = RowNext + 1
excWkb.SaveAs PathName
excWkb.Close
'this is just for testing purposes I will remove later
MsgBox (arrLines(32))
End Sub
感谢您的时间!
答案 0 :(得分:0)
您需要识别上次使用的行并将新数据放在其后。类似的东西: -
RowNext = excWks.Cells.SpecialCells(xlCellTypeLastCell).Row + 1
with excWks
...
(你可能希望Dim RowNext为Long而不是Integer)
xlCellTypeLastCell可能不可靠,因为只有在保存文件时才会重置它 - 这可能足以满足您的需求。如果没有,请参阅OzGrid以获取其他一些建议。