1

我的脚本正在从服务器中提取一些信息(文件名、日期和 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
4

1 回答 1

0

无需创建新的应用程序和工作簿,只需使用活动工作簿,例如替换

'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")

您将 sheetname 替换为所需的工作表名称。

或者,您可以只使用ActiveSheet.

于 2011-07-07T01:40:27.093 回答