我的脚本从服务器中提取一些信息(文件名,日期和& c),该服务器只包含(几乎)由单独的应用程序生成的相同excel文件。目标是找出谁在使用该工具以及使用频率。
我需要两个方面的帮助:从excel文件中提取信息,并在每次运行时将结果附加到SAME excel文件,而不是每次都创建新文件。
这是我的......
Imports Excel = Microsoft.Office.Interop.Excel Imports System Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'declare excel objects
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer = 2
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = " File Name "
xlWorkSheet.Cells(1, 2) = " Date Created "
'this should be cell B1
xlWorkSheet.Cells(1, 3) = " Requestor "
'this should be cell B21
xlWorkSheet.Cells(1, 4) = " Lead Type"
'get to directory
For Each strFolder As String In _
My.Computer.FileSystem.GetDirectories("Z:\\...")
'get file names
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(strFolder)
'write to excel worksheet
xlWorkSheet.Cells(i, 1) = strFolder
xlWorkSheet.Cells(i, 2) = infoReader.CreationTime
i += 1
Next
xlWorkSheet.SaveAs("C:\...")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , see file in c:\Documents")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
答案 0 :(得分:0)
不要创建新的应用程序和工作簿,只需使用activeworkbook,例如 取代
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
带
xlWorkBook = xlApp.ActiveWorkbook
xlWorkSheet = xlWorkBook.Sheets("sheetname")
您可以使用所需的工作表名称替换工作表名称。
或者,您可以使用ActiveSheet
。