简体   繁体   中英

Passing values from sub to function in Excel VBA

I keep getting a ByRef error and I just can't seem to figure it out. The code is all written in the same module.

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

whenever i try to run the code, it gives me an error in

time = CorrectTime(Hint, Mint, Sint)

and the error type will be ByRef mismatch.

What am I not seeing that would solve this problem?

Common gotcha: Dim Hint, Mint, Sint As Integer

Here only Sint is an Integer, the other two variables are not declared with a type so default to Variant ; when passed to a function expecting integers a mismatch error is thrown.

To correct:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM