簡體   English   中英

VBA #Value錯誤在Excel 2010中但不在Excel 2016中

[英]VBA #Value error in Excel 2010 but not in Excel 2016

因此,我在家里的PC上安裝了以下代碼(安裝了Excel 2016),該代碼可以正常工作,但是現在我嘗試在工作中使用它,因此Excel出現了#Value錯誤。 我嘗試搜索Excel 2016和2010之間的差異,但未找到任何有關我的問題的信息。

Public Function comparex(a, b As Long) As Byte
Dim a1, a2, b1, b2, e, e1 As Long
Dim y As Integer
y = 1
a1 = a - 1000
a2 = a + 1000
b1 = b - 1000
b2 = b + 1000
Do Until Sheets(2).Cells(y, 3) = ""
    e = Sheets(2).Cells(y, 3).Value
    e1 = Sheets(2).Cells(y, 4).Value
    If a1 < e And a2 > e And b1 < e1 And b2 > e1 Then
        comparex = 1
        Exit Do
    Else
        y = y + 1

    End If

Loop
End Function

基本上,該腳本應該檢查另一張紙上的一列中a和b附近是否存在值。

此過程應為您工作。 它返回一個布爾值,而不是一個Byte,它表示True或False,這比Byte更常見。

Public Function CompareX(a As Long, b As Long) As Boolean

    Dim a1 As Long, a2 As Long
    Dim b1 As Long, b2 As Long
    Dim e As Long, e1 As Long
    Dim R As Long, Rl As Long

    y = 1
    a1 = a - 1000
    a2 = a + 1000
    b1 = b - 1000
    b2 = b + 1000

    With Sheets(2)
        Rl = .Cells(.Rows.Count, 3).End(xlUp).Row
        For R = 1 To Rl
            e = .Cells(R, 3).Value
            e1 = .Cells(R, 4).Value
            If a1 < e And a2 > e And b1 < e1 And b2 > e1 Then
                CompareX = True
                Exit For
            End If
        Next R
    End With
End Function

雖然以上更為主流。 在這種情況下,它似乎不是很有用。 顯然,您正在嘗試查找滿足所有條件的行。 可以預期的合理結果將是這種情況下的行號。 為此目的,功能將略有不同,如下所示。

Public Function CompareX(a As Long, b As Long) As Long

    Dim a1 As Long, a2 As Long
    Dim b1 As Long, b2 As Long
    Dim e As Long, e1 As Long
    Dim R As Long, Rl As Long

    y = 1
    a1 = a - 1000
    a2 = a + 1000
    b1 = b - 1000
    b2 = b + 1000

    With Sheets(2)
        Rl = .Cells(.Rows.Count, 3).End(xlUp).Row
        For R = Rl To 1 Step -1
            e = .Cells(R, 3).Value
            e1 = .Cells(R, 4).Value
            If a1 < e And a2 > e And b1 < e1 And b2 > e1 Then
                CompareX = R
                Exit For
            End If
        Next R
    End With
End Function

如您所見,該函數向后計數行。 如果沒有找到匹配項,它將返回零,這意味着,只要它返回一個數字,就會找到匹配項。 但是,如果匹配項多於一個,則行號將是列表中最后一個匹配項的行號。

暫無
暫無

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

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