0

我正在尝试编写一个在用户提示操作后将数据导出到 excel 的代码。基本上,我已经能够成功导出到 Excel,但是第二个实例我想写入新选项卡而不是新的 Excel 应用程序。

oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(3)
oSheet.Delete()
oSheet = oBook.Worksheets(2)
oSheet.Delete()
oSheet = oBook.Worksheets(1)
oSheet.Name = "Run " & Counter

此时,用户将按下一个按钮,使 Excel 不再处于活动状态。因此,当我想将更多数据写入新工作表时,除非我完全重复代码,否则 Object 命令不起作用。

我试过:

Counter +=1

'For the first instance
If Counter = 1 Then

        oExcel = CreateObject("Excel.Application")
        oExcel.Visible = True
        oBook = oExcel.Workbooks.Add
        oSheet = oBook.Worksheets(3)
        oSheet.Delete()
        oSheet = oBook.Worksheets(2)
        oSheet.Delete()
        oSheet = oBook.Worksheets(1)
        oSheet.Name = "Run " & Counter

Else
'For every instance after that the user wants to do another run

        oExcel.ActivateObject(Excel.Application)
        oBook = oExcel.Workbooks(1)
        oSheet = oBook.Worksheets.Add
        oSheet.Name = "Run " & Counter

End If

我已经找了好几天了,我很沮丧。我不知道如何引用打开的 excel 以继续写入数据......在用户按下 VB 表单上的按钮确认他们想要再次运行之后。

4

2 回答 2

0

我曾经写过 VBA,但我被教导要改掉使用 CreateObject 的习惯。您也可以使用布尔值,但我想这只是偏好。您应该在循环外创建 excel 对象,一旦分配,就在类级别保持引用。然后,您可以使用循环单独分配下一张表并添加值。将维度保持在类级别意味着您不需要立即删除对象,因为用户可能仍需要使用引用。

Public Class Form1
Dim firstRun As Boolean = True
Dim xlApp As New Excel.Application
Dim xlWb As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'set up us some excel
    xlApp.Visible = True
    xlApp.SheetsInNewWorkbook = 1
    xlWb = xlApp.Workbooks.Add

    'imaginary loop
    For i = 0 To 5

        Dim msgResponse = MessageBox.Show("Do you want to loop?", "Keep Looping?", MessageBoxButtons.YesNo)

        If msgResponse = Windows.Forms.DialogResult.No Then Exit For

        If firstRun Then
            xlSheet = xlWb.Sheets(1)
            firstRun = False
        Else
            xlWb.Activate()
            xlSheet = xlWb.Sheets.Add(After:=xlWb.Sheets(xlWb.Sheets.Count))
        End If

        xlSheet.Name = "TEST" & i
        xlSheet.Range("A1").Value = "Some Data"


    Next i

End Sub
End Class

一旦您确定用户已完成工作表,您将需要确保清理您的参考资料。

于 2014-05-13T15:45:22.827 回答
0

要获取对已经运行的 excel 实例的引用,您可以使用GetObject.

例如:

' Test to see if a copy of Excel is already running. 
Private Sub testExcelRunning()
    On Error Resume Next 
    ' GetObject called without the first argument returns a 
    ' reference to an instance of the application. If the 
    ' application is not already running, an error occurs. 
    Dim excelObj As Object = GetObject(, "Excel.Application")
    If Err.Number = 0 Then
        MsgBox("Excel is running")
    Else
        MsgBox("Excel is not running")
    End If
    Err.Clear()
    excelObj = Nothing 
End Sub

http://msdn.microsoft.com/en-us/library/e9waz863(v=vs.90).aspx

如果 Excel 尚未运行,您可以使用CreateObject.

于 2014-05-13T17:54:43.023 回答