簡體   English   中英

Excel VBA 嘗試為數組編寫函數時出現 #Value 錯誤

[英]Excel VBA Getting a #Value error when trying to write a function for an array

我試圖從工作表中找到數組中最短的字符串。 但是,當我嘗試執行該函數時,出現 #Value 錯誤。 我究竟做錯了什么? 謝謝!

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

您的代碼中有幾個問題。

  • 首先,在調用cell = array1.Cells(i, 1).Value之前,您永遠不會分配i 這將是一個運行時錯誤 1004。
  • 其次,在做任何其他事情之前,您應該測試輸入Range以確保它是一個“數組”。 如果它是單個單元格,您可以跳過其他所有內容,只返回該單元格的文本。
  • 第三,您永遠不會在函數中的任何地方更新cell的值 - 它始終是vbNullString的未初始化值。
  • 第四,單元格文本的最大長度是 32767 個字符,而不是 100 個。您應該將其用作初始值。

我的猜測是你正在尋找更像這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM