如何显示指定范围内的值? [英] How do I display the values from a specified Range?
问题描述
大家好,
简单来说,我想使用Vb.net从excel工作簿中提取一系列指定单元格的值,并将这些值显示在表单上.我没有问题可以打开或运行excel应用程序/工作簿;我什至可以从工作簿中读取一个单元格或多个单元格,并将该值显示在我的表单上.但是我必须分别指定每个.
我的问题是:如何读取特定范围的单元格(即"A1:A6")中的值,然后将其显示在表单上?
非常感谢.
以下是我编写的代码.我知道这是不正确的,我们将不胜感激.
''导入
Hi everyone,
In simple terms I would like to use Vb.net to extract the values of a range of specified cells from an excel workbook and display those values onto a form. I have no problems opening or running the excel application/workbook; I can even read a single cell or multiple cells from the workbook and display that value onto my form; however I have to specify each individually.
My question is: how can I read and then display the values from a specific range of cells (i.e. "A1:A6") onto a form?
Thank you very much.
Below is the code I had written. I know it is incorrect, any help would be greatly appreciated.
''Import
Imports Excel = Microsoft.Office.Interop.Excel
Dim xlApp As Application = New Application
Dim xlWorkBook As Workbook = xlApp.Workbooks.Open("FileName")
Dim xlSheet As Worksheet = xlWorkBook.ActiveSheet
Dim myRange As Excel.Range
Dim rCount As Integer
Dim cCount As Integer
Dim Obj1, Obj2, Obj3 As Object
myRange = xlSheet.Range("A2:A6")
For rCount = 1 To myRange.Rows.Count
For cCount = 1 To myRange.Columns.Count
Obj1 = CType(myRange.Cells, Excel.Range)
Obj2 = CType(myRange.Cells, Excel.Range)
Obj3 = CType(myRange.Cells, Excel.Range)
displayLabel.Text = Obj1.value + Environment.NewLine +
Obj2.value + Environment.NewLine +
Obj3.value
Next
Next
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlSheet)
推荐答案
如果您调试代码,则会发现Obj1
包含所有个值您的范围,而不仅仅是一个单元格.
我还更喜欢使用StringBuilder类,而不是连接字符串(您将需要Imports System.Text
)
因此,迭代所有单元格的最简单方法可能是
If you debug your code you will find thatObj1
contains all of the values in your range, not just a single cell.
I also prefer to use the StringBuilder class rather than concatenating strings (you will needImports System.Text
)
So potentially the easiest way to iterate through all of the cells would be
Dim sb As StringBuilder = New StringBuilder("")
For Each c As Excel.Range In myRange.Cells
sb.Append(c.Value2)
sb.Append(Environment.NewLine)
Next
displayLabel.Text = sb.ToString()
请注意,如果您的范围跨多个列(例如,如果您有
Note this also works if your range spans across multiple columns e.g. if you had
myRange = xlSheet.Range("A2:B6")
,则可以从
获取值
you would get the values from
A2
B2
A3
B3 etc
这篇关于如何显示指定范围内的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!