如何使用 vb.net 将数据附加到现有的 excel 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15307021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:41:18  来源:igfitidea点击:

how to append data to existing excel file using vb.net?

vb.netexcel

提问by user2107624

i have code which finds the last non empty row in an existing excel file. i want to insert data from 5 textbox to the next 5cells in column. i dont know how to code it. please help me, here is my code:

我有代码可以在现有的 excel 文件中找到最后一个非空行。我想将 5 个文本框中的数据插入列中的下一个 5 个单元格。我不知道如何编码。请帮助我,这是我的代码:

With xlWorkSheet
        If EXL.WorksheetFunction.CountA(.Cells) <> 0 Then
            lRow = .Cells.Find(What:="*", _
                          After:=.Range("A2"), _
                          LookAt:=Excel.XlLookAt.xlPart, _
                          LookIn:=Excel.XlFindLookIn.xlFormulas, _
                          SearchOrder:=Excel.XlSearchOrder.xlByRows, _
                          SearchDirection:=Excel.XlSearchDirection.xlPrevious, _
                          MatchCase:=False).Row
        Else
            lRow = 1
        End If

    End With

回答by Jason Bayldon

Here are two different solutions to your problem. I like the second better because you can determine a lastrow from any column and if you cared reference it to another column.

这里有两种不同的解决方案可以解决您的问题。我更喜欢第二个,因为您可以从任何列中确定最后一行,如果您愿意将其引用到另一列。

Dim nextrow As Integer = excel.Rows.End(XlDirection.xlDown).Row + 1

Dim ws As Worksheet = excel.ActiveSheet
Dim nRow = ws.Range("A" & ws.Rows.Count).End(XlDirection.xlUp).Row + 1

Then all you have to do to assign a value is:

然后你需要做的就是赋值:

excel.Range("A" & nRow).Value = "test"
excel.range("B" & nRow).value = "adjacent column"

If you want to loop it to 5 cells below that then do:

如果要将其循环到下面的 5 个单元格,请执行以下操作:

Dim ws As Worksheet = excel.ActiveSheet
Dim lRow = ws.Range("A" & ws.Rows.Count).End(XlDirection.xlUp).Row

For i = 1 To 5
    excel.Range("A" & lRow).Offset(i, 0).Value = "variable here"
Next