[英]Excel VBA Getting a #Value error when trying to write a function for an array
I am trying to find the shortest string in an array from a worksheet.我试图从工作表中找到数组中最短的字符串。 However, when I try to execute the function I get a #Value error.
但是,当我尝试执行该函数时,出现 #Value 错误。 What am I doing wrong?
我究竟做错了什么? Thanks!
谢谢!
Function ShortestString(ByVal array1 As Range)
Dim nRows As Integer
Dim i As Integer
Dim cell As String
Dim cellLength As Integer
Dim string1 As String
nRows = array1.Rows.Count
cellLength = 100
cell = array1.Cells(i, 1).Value
For i = 1 To nRows
If cellLength > Len(cell) Then
cellLength = Len(cell)
string1 = cell
End If
Next i
ShortestString = string1
End Function
Several issues in your code.您的代码中有几个问题。
i
before you call cell = array1.Cells(i, 1).Value
.cell = array1.Cells(i, 1).Value
之前,您永远不会分配i
。 That's going to be a run-time error 1004.Range
to make sure it's an "array" before you do anything else.Range
以确保它是一个“数组”。 If it's a single cell, you can skip everything else and just return the text of that cell.cell
anywhere in your function - it will always be the uninitialized value of vbNullString
.cell
的值 - 它始终是vbNullString
的未初始化值。 My guess is that you're looking for something more like this:我的猜测是你正在寻找更像这样的东西:
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
Note that you can probably actually use an array instead of testing individual cells, but that's an optimization you can make if the performance isn't up to snuff.请注意,您实际上可以使用数组而不是测试单个单元格,但如果性能不理想,您可以进行优化。
Edit:编辑:
You can convert the function to use an array of cell values by reading the entire range into a Variant()
:您可以通过将整个范围读入
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.