简体   繁体   English

尝试创建创建新的Excel工作表并将数据复制到工作表的循环

[英]Trying to create loop that creates new excel sheet and copies data to sheet

I have a loop that populates my excel workbook, current worksheet with data that is calculated throughout the time my program is ran. 我有一个循环,用我的程序运行期间计算出的数据填充excel工作簿(当前工作表)。 My loop is supposed to check for if the current year tab exists, if it does it's supposed to write to that sheet. 我的循环应该检查当前的Year选项卡是否存在,如果存在,则应该写入该工作表。 If not, it's supposed to create another sheet with the current year as the name of the sheet and copy over header titles that are in A1 - A65 of the worksheet right before the newly created worksheet. 如果不是这样,则应以当前年份为工作表名称来创建另一个工作表,并在新创建的工作表之前复制工作表的A1-A65中的标题。 It does the job going to the current year sheet (if it already exists), but will not create a new sheet with teh current year and copy the cells over if the current year sheet does not exist. 它将执行当前年表的工作(如果已经存在),但是不会使用当前年创建新表,并且如果当前年表不存在,则不会复制单元格。 I've included the loop and a few lines after to see if anyone can help me spot or correct the error 我将循环和几行内容包括在内,以查看是否有人可以帮助我发现或纠正错误

   Dim excel_app As Excel.Application
    Dim workbook As Excel.Workbook
    Dim sheet_name As String
    Dim sheet As Excel.Worksheet

    Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
    Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")

    ' Get the Excel application object.
    excel_app = New Excel.Application

    ' Make Excel visible (optional).
    excel_app.Visible = False

    ' Open the workbook.
    workbook = excel_app.Workbooks.Open(xlPath)


    'Under Construction, trying to check if current year tab exists, if not creating it
    Dim i As Integer
    Dim blnsheet As Boolean = False
    Dim yearstamp As String = _
    DateTime.Now.ToString("yyyy")

    Dim datestamp As String = _
            DateTime.Now.ToString("MMMM yyyy")

    With workbook
        For i = 1 To .Sheets.Count
            If .Sheets(i).name = yearstamp Then
                blnsheet = True
                Exit For
            End If
        Next i

        If blnsheet = False Then
            .Sheets.Add()
            With .ActiveSheet
                .name = yearstamp
                .Range("A1:A65") = .Sheets(i - 1).Range("A1:A65")
            End With
        End If
    End With

    'End of Sheet loop

    sheet_name = yearstamp
    sheet = excel_app.Worksheets(sheet_name)

    Dim ColumnCount As Long
    ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count

    For m As Integer = 0 To ColumnCount
        If sheet.Range("A1").Offset(0, m).Value = datestamp Then
            ColumnCount = m
            Exit For
        End If
    Next m

    'End Construction


    With sheet.Range("A1")
        .Offset(0, ColumnCount).Value = datestamp
        .Offset(1, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.totalincome, 2)
        .Offset(2, ColumnCount).Value = "$" & FormatNumber(totalexpenses, 2)
        .Offset(3, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.cellphone, 2)
        .Offset(4, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.carinsurance, 2)
        .Offset(5, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.healthinsurance, 2)
        .Offset(6, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.therapysessions, 2)
        .Offset(7, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.drappointments, 2)
        .Offset(8, ColumnCount).Value = "$" & FormatNumber(GlobalVariables.medications, 2)
        .Offset(9, ColumnCount).Value = GlobalVariables.med1name & " $" & FormatNumber(GlobalVariables.med1, 2)
        .Offset(10, ColumnCount).Value = GlobalVariables.med2name & " $" & FormatNumber(GlobalVariables.med2, 2)
        .Offset(11, ColumnCount).Value = GlobalVariables.med3name & " $" & FormatNumber(GlobalVariables.med3, 2)
        .Offset(12, ColumnCount).Value = GlobalVariables.med4name & " $" & FormatNumber(GlobalVariables.med4, 2)
        .Offset(13, ColumnCount).Value = GlobalVariables.med5name & " $" & FormatNumber(GlobalVariables.med5, 2)
        .Offset(14, ColumnCount).Value = GlobalVariables.med6name & " $" & FormatNumber(GlobalVariables.med6, 2)
        .Offset(15, ColumnCount).Value = GlobalVariables.med7name & " $" & FormatNumber(GlobalVariables.med7, 2)
        .Offset(16, ColumnCount).Value = GlobalVariables.med8name & " $" & FormatNumber(GlobalVariables.med8, 2)

Edit to add most recent progress/failed attempt 编辑以添加最新进度/失败尝试

  'Under Construction, trying to check if current year tab exists, if not creating it
    Dim blnsheet As Boolean = False

    With workbook
        If .Item(yearstamp) = True Then
            blnsheet = True
        Else : blnsheet = False
        End If

        If blnsheet = False Then
            .Sheets.Add()
            .ActiveSheet.Name = yearstamp
            .ActiveSheet.Range("A1:A65") = .Sheets(yearstamp - 1).Range("A1:A65")
        End If
    End With

You can get rid of the loop entirely, I think, by finding the sheet by name. 我认为,您可以通过按名称查找工作表来完全摆脱循环。 The Item property will accept a string representing the name of the sheet. Item属性将接受一个表示工作表名称的字符串。

See Sheets.Item property : 参见Sheets.Item属性

Index 指数
Type: System.Object 类型: System.Object
Required Object . 必需的对象 The name or index number of the object. 对象的名称或索引号。

This will return a Worksheet object. 这将返回一个工作表对象。 You can test to see if the return value is Nothing to determine if it exists: 您可以测试一下返回值是否为Nothing以确定它是否存在:

Dim l_worksheets = workbook.Worksheets
Dim l_worksheet = l_worksheets("2013")
Dim l_worksheetExists = l_worksheet Is Not Nothing

A problem you might not have noticed yet (maybe you have and you are concerned with more pressing issues) is that Excel is not quitting properly when your code has finished executing, even though you are calling Quit. 您可能尚未注意到的一个问题(也许您已经注意到了,并且您担心更紧迫的问题)是,即使您正在调用Quit,当代码执行完毕时Excel也无法正确退出。 If you haven't noticed that yet, you will. 如果您还没有注意到,那您会的。 This is because you are creating references to objects but not cleaning them up when you are done. 这是因为您正在创建对对象的引用,但在完成操作时并未清除它们。 I see several examples in your code, but to point one out specifically: 我在您的代码中看到了几个示例,但要特别指出一个示例:

        For i = 1 To .Sheets.Count

You never clean up your Sheets COM object, so it hangs around in memory. 您永远不会清理Sheets COM对象,因此它会在内存中徘徊。 (Because it is a COM object, it cannot be garbage collected.) (由于它是一个COM对象,因此无法进行垃圾回收。)

See Never use 2 dots with com objects 请参阅从不对com对象使用2点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM