我需要将 Excel 工作表中的数据提取到一个数组中,该数组将在使用 VBScript 作为脚本语言的应用程序 (Quick Test Professional) 中使用。我们可以使用以下代码:
' ws must be an object of type Worksheet
Public Function GetArrayFromWorksheet(byref ws)
GetArrayFromWorksheet = ws.UsedRange.Value
End Function
myArray = GetArrayFromWorksheet(myWorksheet)
MsgBox "The value of cell C2 = " & myArray(2, 3)
一切都很好,但不幸的是,返回的数组不仅包含文字文本字符串,还包含日期、整数、 double 等类型的基元。数据转换发生了多次。
[编辑]示例:在单元格中输入=NOW()
并将单元格格式设置为hh:mm
时,将显示值 17:45,上述方法返回 double
类型的变量和类似 41194.7400990741
以下解决方案效果更好:我可以使用 .Text
属性从单元格获取文字文本,但它们仅适用于一个单元格,不适用于一系列单元格。我无法像使用 .Value
属性那样立即对数组执行此操作,因此我必须一次填充数组一个单元格:
Public Function GetArrayFromWorksheet_2(byref ws)
Dim range, myArr(), row, col
Set range = ws.UsedRange
' build a new array with the row / column count as upperbound
ReDim myArr(range.rows.count, range.columns.count)
For row = 1 to range.rows.count
For col = 1 to range.columns.count
myArr(row, col) = range.cells(row, col).text
Next
Next
GetArrayFromWorksheet_2 = myArr
End Function
但是哎哟...嵌套的for循环
。是的,在大型工作表上,性能明显下降。
有人知道更好的方法吗?
最佳答案
正如我们在评论中所述,为了避免出现此问题,您需要在某个时刻循环遍历数组。不过,我发布此内容是因为它可能会给您带来显着的速度提升,具体取决于工作表上的数据类型。由于 200 个单元格中有一半是数字,因此速度提高了约 38%。对于 600 个相同比例的细胞,改善率为 41%。
通过循环遍历数组本身,并仅检索解释为 double (数字)的值的 .Text
,如果存在大量非 double 据,您可以看到速度的提高。这不会检查 .Text
单元格中是否包含文本、日期格式为日期或空白单元格。
Public Function GetArrayFromWorksheet_3(ByRef ws)
Dim range, myArr, row, col
Set range = ws.UsedRange
'Copy the values of the range to temporary array
myArr = range
'Confirm that an array was returned.
'Value will not be an array if the used range is only 1 cells
If IsArray(myArr) Then
For row = 1 To range.Rows.Count
For col = 1 To range.Columns.Count
'Make sure array value is not empty and is numeric
If Not IsEmpty(myArr(row, col)) And _
IsNumeric(myArr(row, col)) Then
'Replace numeric value with a string of the text.
myArr(row, col) = range.Cells(row, col).Text
End If
Next
Next
Else
'Change myArr into an array so you still return an array.
Dim tempArr(1 To 1, 1 To 1)
tempArr(1, 1) = myArr
myArr = tempArr
End If
GetArrayFromWorksheet_3 = myArr
End Function
关于excel - 将工作表转换为仅包含字符串的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12861095/