gpt4 book ai didi

vba - 在 Excel VBA 中设置默认 TextBox.Value TypeName

转载 作者:行者123 更新时间:2023-12-04 22:31:52 25 4
gpt4 key购买 nike

我有一个 vba 函数,用于检查来自文本框的用户输入是否为正整数。下面的代码:

Public Function IsPosInteger(n As Variant) As Boolean  
If IsNumeric(n) = True Then
If (n = Int(n)) And n > 0 Then
IsPosInteger = True
Else
IsPosInteger = False
End If
Else
IsPosInteger = False
End If
End Function

问题是,在测试该函数时,对于有效的正整数仍然返回 false。经过进一步调查,我注意到 texbox 值的默认变量类型是字符串。可能是 IsNumeric 返回 false 的主要原因。

下面的函数是我用来确定变量类型的。
TypeName(n)

最佳答案

这对我有用。

我使用了一个输入框,其中包含:

  • 字符串(假)
  • 负数(假)
  • 正数(真)
  • 正数和字母(假)

  • Public Function IsPosInteger(n As Variant) As Boolean
    If n > 0 And IsNumeric(n) Then IsPosInteger = True
    End Function

    现在,可能会出现另一个问题,即由于输入框的性质,值 n 在技术上仍然是类型 字符串 ——即使它通过了此函数的测试。如果您希望更改此行为,请继续阅读。

    为此,请确保您使用的是 ByRef (当这是 故意 时,我通常在参数上输入 ByRef ,即使 VBA 自动假定传递给函数的任何参数都是 ByRef 如果它没有显式状态 ByVal )。

    如果这是您想要的结果,那么您可以使用此功能:
    Public Function IsPosInteger(ByRef n As Variant) As Boolean
    If n > 0 And IsNumeric(n) Then
    IsPosInteger = True
    n = clng(n) '<-- This converts the variant (currently a string) n to type long,
    ' only if it passes the test
    end if
    End Function

    您必须确保调用例程中的 n 的类型为 Variant ,否则您将遇到错误。

    关于vba - 在 Excel VBA 中设置默认 TextBox.Value TypeName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52048270/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com