简体   繁体   English

将值从子传递到Excel VBA中的函数

[英]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. 我不断收到ByRef错误,但似乎无法弄清楚。 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. 错误类型为ByRef不匹配。

What am I not seeing that would solve this problem? 我看不到能解决这个问题的什么?

Common gotcha: Dim Hint, Mint, Sint As Integer 常见陷阱: 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 ; 这里只有Sint是Integer,其他两个变量没有声明为类型,因此默认为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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