vba 使用 VB.net 获取 Excel 单元格值,哪个值不正确?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18870649/
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-11 23:23:44  来源:igfitidea点击:

Using VB.net to get Excel Cell Value which is not the correct value?

vb.netvisual-studio-2010exceldebuggingvba

提问by zxzxzx

I've been stuck on this for the past few hours so I really could do with some help. I am trying to get numeric (integer and decimal) values from an Excel spreadsheet and use it create a graph on my form using the chart control or even display that value in a textbox.

在过去的几个小时里,我一直被困在这个问题上,所以我真的可以得到一些帮助。我正在尝试从 Excel 电子表格中获取数字(整数和小数)值,并使用它在我的表单上使用图表控件创建图形,甚至在文本框中显示该值。

The Value of cell A11 is "2003" and K11 is "12.00" but the returned values are 0 and 12. I use formulas to calculate the rest of the y values. The strange thing is that text works fine. Cell A3 has "initial" which comes back as "initial", it's just the numbers which don't work.

单元格 A11 的值是“2003”,K11 是“12.00”,但返回值是 0 和 12。我使用公式来计算其余的 y 值。奇怪的是文本工作正常。单元格 A3 有“初始”,它返回为“初始”,只是数字不起作用。

    xlApp = New Excel.Application
    xlWorkBook = xlApp.Workbooks.Open("C:\File.xls")    
    xlWorkBook = xlApp.Workbooks.Add("C:\File.xls")
    xlSheet = xlWorkBook.Worksheets(1)

    Dim x1 As String
    Dim y1 As String
    x1 = xlSheet.Range("A11").Value.ToString     
    y1 = xlSheet.Range("K11").Value.ToString
    MsgBox(x1)

Thanks in advance

提前致谢

回答by SysDragon

Try using .Textinstead of .Value. It will retrieve the value shown instead of the cell value:

尝试使用.Text代替.Value. 它将检索显示的值而不是单元格值:

x1 = xlSheet.Range("A11").Text
y1 = xlSheet.Range("K11").Text

This will ignore even the formats, for example, the value 7.7777in a cell with a format to show 2 decimal places will show 7.78, and that is what .Textwill retrieve.

这甚至会忽略格式,例如,7.7777具有显示 2 个小数位的格式的单元格中的值将显示7.78,这就是.Text将检索的内容。