簡體   English   中英

VBA錯誤1004功能

[英]VBA Error 1004 in function

我正在嘗試編寫一個函數,該函數返回與我在參數中給出的列位於同一列的特定單元格的值(lig =行號,col =列號),但是每次運行它時,我都會得到一個錯誤“ 1004”,這是我的代碼:

Function week(lig As Integer, col As Integer) As Integer
    Dim i As Integer
    i = 0
    Do Until Cells(lig - i, 1) = "Row labels"
        i = i + 1
    Loop
    week = Cells(lig - i, col)
End Function

出現錯誤的行是:

 Do Until Cells(lig - i, 1) = "Row labels"

我知道我要先測試包含整數的單元格的值,然后才懷疑是類型錯誤,但是我無法解決它。 有人可以幫忙嗎?

該錯誤不是類型錯誤。 問題是您正在嘗試訪問不存在的單元。 您的循環顯然無法到達包含“行標簽”值的單元格,並最終嘗試訪問Cells(0,1)-觸發錯誤1004。關於這種情況的發生原因–您沒有提供足夠的詳細信息來說。

我懷疑單元格中的值實際上是“行標簽”或“行標簽”或“行標簽”或其他與實際不完全匹配的值。請嘗試以下操作:

Do Until Trim(Ucase(Cells(lig - i, 1))) = "ROW LABELS" 

或者,如果您只是想停在第一行,請使用以下命令:

Do Until lig - i = 1

i = 0將導致錯誤,因為表格中不存在cell(0,1)。 如果您的邏輯找不到,您可能還需要一個exit子句,因為當您到達工作表的末尾時會得到一個錯誤。 如果您通過此lig = 1,您也會收到錯誤消息(因為lig-i(1-1)會導致0),因此您可能還需要處理該情況

Function week(lig As Integer, col As Integer) As Integer
    Dim i As Integer
    i = 1'Changed to 1
    Do Until Cells(lig - i, 1) = "Row labels"
        i = i + 1
        if i > 1000000 then exit do 'Exit clause
    Loop
    if i < 1000000 then 
        week = Cells(lig - i, col)
    else
        week = 0'Handle 0's in calling code
    end if
End Function

您可能要考慮如下重寫,我認為這更清楚。

Function week(lig As Integer, col As Integer) As Integer

    Dim i As Integer

    ' Thsi function will return 0 if no row with the text is found
    week = 0

    For i = lig To 1 Step -1

        If Cells(i, 1) = "Row labels" Then
            week = Cells(i, col)
            Exit For
        End If

    Next i


End Function

' EVEN BETTER USE THIS (or similar)!

Function week(MyCell As Range) As Integer

    Dim i As Integer

    week = 0

    For i = MyCell.Row To 1 Step -1

        If MyCell.Parent.Cells(i, 1) = "Row labels" Then
            week = MyCell.Parent.Cells(i, MyCell.Column)
            Exit For
        End If

        ' Note
        ' MyCell.Parent. returns the sheet containing the cell
        ' Just using Cells(i, 1) (wihtout preceeding with "MyCell.Parent." will pick up
        ' cells on the currently active sheet, which may not be the sheet with the cell!
        '

    Next i


End Function

暫無
暫無

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

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