首页 > 解决方案 > 如何显示excel表格中的值?

问题描述

我正在编写代码,它将从 excel 中选择一个随机行,然后显示该行中每一列的值。问题是 msgbox 中的所有值都是 0,即使它们在 excel 中定义不同。我可能在我的代码中遗漏了一些要点。

xlApp = New Excel.Application
xlWorkbooks = xlApp.Workbooks.Open("C:\Values.xlsx")
xlsheet = CType(xlWorkbook.Sheets("Sheet1"), Excel.Worksheet)
xlsheet.Activate()
xlApp.Visible = True

Dim firstrow As Long, lastrow As Long, Rndrow As Long
firstrow = 2
lastrow = GetFirstEmptyRow(xlsheet) - 1
Rndrow = Int((lastrow - firstrow + 1) * Rnd() + firstrow)
xlCurRow = Rndrow

minA = xlsheet.Range("B" & xlCurRow).Value
MessageBox.Show(minA)
maxA = xlsheet.Range("C" & xlCurRow).Value
MessageBox.Show(maxA)
minB = xlsheet.Range("D" & xlCurRow).Value
MessageBox.Show(minB)
maxB = xlsheet.Range("E" & xlCurRow).Value
minC = xlsheet.Range("F" & xlCurRow).Value
maxC = xlsheet.Range("G" & xlCurRow).Value
Private Function GetFirstEmptyRow(xlsheet As Worksheet, Optional sColName As String = "A") As Long
    GetFirstEmptyRow = xlsheet.Range(sColName&xlsheet.Rows.Count).End(XlDirection.xlUp).Row + 1
End Function

标签: excelvb.net

解决方案


不要使用Rnd(). 好吧,如果你必须,那么你也必须先Randomize()打电话

Randomize()
Rndrow = Int((lastrow - firstrow + 1) * Rnd() + firstrow)

否则每次运行都会得到相同的值。你得到 0。我得到 12。在不同的机器上会有所不同。

而是使用Random

Dim r As New Random()
Rndrow = Int((lastrow - firstrow + 1) * r.NextDouble() + firstrow)

此外,您的代码无法使用Option Strict On. 您应该首先将其放在文件的顶部。(只要您可以提供正确的类型,请尽量不要让您的代码进行隐式转换。它会增加不必要的处理。)然后进行这些更改

' return an Integer instead of Long
' Range.Row is Integer so this can never be Long unless you have 2 billion rows
Private Function GetFirstEmptyRow(xlsheet As Worksheet, Optional sColName As String = "A") As Integer
    ' use the VB.NET syntax to return, not VBA style
    ' concatenate non-string values with interpolation which performs ToString() implicitly
    Return xlsheet.Range($"{sColName}{xlsheet.Rows.Count}").End(XlDirection.xlUp).Row + 1
End Function
Dim r As New Random()
Dim firstrow = 2
Dim lastrow = GetFirstEmptyRow(xlsheet) - 1
' must cast to some integral number here, Integer is fine
Dim xlCurRow = CInt((lastrow - firstrow + 1) * r.NextDouble() + firstrow)

' again string concatenation when dealing with non-strings
Dim minA = xlsheet.Range($"B{xlCurRow}").Value
' minA is an object
' MessageBox.Show(text As String) takes a string, not an object
MessageBox.Show(minA.ToString())
' or MessageBox.Show($"{minA}")

我猜你来自 VBA 或 VB6。Rnd 类和通过分配给函数名称从函数返回将在 VB.NET 中工作,但不推荐使用。


推荐阅读