我正在尝试从工作表中查找数组中最短的字符串。但是,当我尝试执行该函数时,出现#Value错误。我究竟做错了什么?谢谢!
$arr = [];
$arr[13] = 13;
$arr[45] = 45;
$arr[7] = 7;
$arr[123] = 456;
foreach($arr as $a){
echo $a.', ';
}
答案 0 :(得分:0)
您的代码中有几个问题。
i
之前分配cell = array1.Cells(i, 1).Value
。这将是运行时错误1004。Range
,以确保它是一个“数组”,然后再执行其他操作。如果是单个单元格,则可以跳过其他所有内容,只返回该单元格的文本即可。cell
的值-它始终是vbNullString
的未初始化值。我的猜测是您正在寻找更像这样的东西:
Option Explicit
Public Function ShortestString(ByVal target As Range) As String
Dim rowCount As Long, columnCount As Long
rowCount = target.Rows.Count
columnCount = target.Columns.Count
If rowCount = 1 And columnCount = 1 Then
ShortestString = target.Text
Exit Function
End If
Dim rowIdx As Long, colIdx As Long
Dim shortest As String, current As String
shortest = String(32767, " ")
For rowIdx = 1 To rowCount
For colIdx = 1 To columnCount
current = target.Cells(rowIdx, colIdx).Text
If Len(current) <= Len(shortest) Then
shortest = current
End If
Next
Next
ShortestString = shortest
End Function
请注意,您实际上可以使用而不是测试单个单元格,但这是您可以进行的优化,如果性能不佳。
编辑:
您可以通过将整个范围读入Variant()
来将函数转换为使用单元格值数组:
Dim cellValues() As Variant
cellValues = target.Value
For rowIdx = 1 To rowCount
For colIdx = 1 To columnCount
current = CStr(cellValues(rowIdx, colIdx))
If Len(current) <= Len(shortest) Then
shortest = current
End If
Next
Next