开发者

Manipulating Excel files using VB8

开发者 https://www.devze.com 2023-03-17 16:21 出处:网络
My script is pulling some information (filename, date, &c) from a server that contains only (nearly) identical excel files generated by a separate application whenever it is used. The goal is to f

My script is pulling some information (filename, date, &c) from a server that contains only (nearly) identical excel files generated by a separate application whenever it is used. The goal is to find out who is using the tool and how often.

I need help with two things: extracting info from within the excel file, and appending the开发者_如何学JAVA results to the SAME excel file each time it's run instead of creating a new file each time.

Here is what I have...

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


Instead of creating a new application and workbook, just use activeworkbook, e.g. replace

'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")

with

xlWorkBook = xlApp.ActiveWorkbook
xlWorkSheet = xlWorkBook.Sheets("sheetname")

where you replace sheetname with whatever the desired sheet name is.

Alternatively, you could just use ActiveSheet.

0

精彩评论

暂无评论...
验证码 换一张
取 消