我正在尝试将 Excel VBA 中的字符串解析为两个变量。
Sub StartEndMonth(ByVal MonthRange As String, ByRef MonthStart As String, ByRef MonthEnd As String) ' xxx-xxx
MonthStart = "Jan"
MonthEnd = "Dec"
End Sub
Sub TestMonthList()
Dim Month_Range, Start_Month, End_Month As String
Month_Range = "Jan-Dec"
StartEndMonth Month_Range, Start_Month, End_Month
MsgBox MonthRange & " " & Start_Month & " " & End_Month
End Sub
代码在调用例程中的 Start_Month 变量上抛出 VBA ByRef 参数类型不匹配错误。我应该在 StartEndMonth 例程中有一些解析逻辑。在消除例程中的其他所有内容后,我仍然遇到编译错误。
作为一般规则,不要编写修改其参数的子程序/函数。如果你计算了一些东西,返回它,例如作为数组:
Function SplitMonthRange(MonthRange As String)
SplitMonthRange = Split(MonthRange, "-")
' you really should add some sanity checks, e.g. UBound() and value checks
End Function
那么资源的工作方式非常简单:
Sub TestSplitMonthRange()
Dim monthRange as String, months As Variant
monthRange = "Jan-Dec"
months = SplitMonthRange(monthRange)
MsgBox monthRange & ": " & months(0) & " to " & months(1)
End Sub
提示 - 这个:
Dim Month_Range, Start_Month, End_Month As String
声明 2 个变体和 1 个字符串。这是正确的:
Dim Month_Range As String, Start_Month As String, End_Month As String