在Excel VBA中将值从子函数传递给函数

时间:2015-03-29 12:33:52

标签: excel vba excel-vba

我不断收到ByRef错误,我似乎无法弄明白。 代码全部写在同一个模块中。

Sub GetTime(Labelname As Object)
Dim Hint, Mint, Sint As Integer
Dim time As String

Hint = CInt(Hour(Now))
Mint = CInt(Minute(Now))
Sint = CInt(Second(Now))

time = CorrectTime(Hint, Mint, Sint)

Private Function CorrectTime(Hours As Integer, Minutes As Integer, Seconds As Integer) As String
Dim HS, MS, SS As String

If Len(CStr(Hours)) = 1 Then
    HS = "0" & CStr(Hours)
Else
    HS = CStr(Hours)
End If

If Len(CStr(Minutes)) = 1 Then
    MS = "0" & CStr(Minutes)
Else
    MS = CStr(Minutes)
End If

If Len(CStr(Seconds)) = 1 Then
    SS = "0" & CStr(Seconds)
Else
    SS = CStr(Seconds)
End If

CorrectTime = HS & ":" & MS & ":" & SS
End Function

每当我尝试运行代码时,它都会在

中给出错误
time = CorrectTime(Hint, Mint, Sint)

,错误类型将是ByRef不匹配。

我没有看到什么可以解决这个问题?

1 个答案:

答案 0 :(得分:4)

常见问题:Dim Hint, Mint, Sint As Integer

这里只有Sint是一个整数,其他两个变量没有用类型声明,因此默认为Variant;当传递给期望整数的函数时,会抛出不匹配错误。

要更正:

Dim Hint As Integer, Mint As Integer, Sint As Integer