VBA:我的程序抛出编译错误ByRef

时间:2017-10-05 21:55:00

标签: excel vba compiler-errors byref

我正在使用正在运行的程序。我制作了一个副本来测试使我的代码更加模块化。下面是循环中的一个子运行,通过调用第一个循环变为两个子运行。

Sub Trendline()
Dim eqn, name As String
Dim cht As ChartObject
Dim i As Integer
For Each cht in Worksheets(1).ChartObjects
    If cht.Chart.SeriesCollection(1).Trendlines.Count > 0 Then
        cht.Activate
        name = Split(ActiveChart.name)(1)
        i = Worksheets(name).Range("Z2").Value 'indicates what kind of trendline
        eqn = ActiveChart.SeriesCollection(1).Trendlines(1).DataLabel.Text
        'the trendline has both R-square and Equation displayed
        eqn = Split(eqn, Chr(10))(0)
        Worksheets(name).Range("AA1").Value = MakeEqn(i, eqn)
    End If
Next cht
End Sub

Function MakeEqn(i As Integer, eqn As String) As String
'1 is linear, 2 polynomial, 3 polynomial order 3
'4 is power, 5 exponential, 6 logarithmic
    eqn = Replace(eqn, "y = ", "")
If i = 6 Then ' removes 6 from options
    eqn = Replace(eqn, "ln", "*LN")
    'Break
Else
    eqn = Replace(eqn, "x", "*x")
    If i = 1 Then ' removes 1 from options
        'Break
    ElseIf i = 5 Then ' removes 5 from options
        eqn = Replace(eqn, "e", "*EXP(")
        eqn = eqn & ")" ' add ")" to end of string
        ' Break
    ElseIf i = 4 Then ' removes 4 from options
        eqn = Replace(eqn, "x", "x^")
        'Break
    Else ' for both 2 and 3
        eqn = Replace(eqn, "x2", "x^2") ' 2 is now done
        If i = 3 Then
            eqn = Replace(eqn, "x3", "x^3")
        End If
    End If
End If
MakeEqn = eqn
End Function

这里,MakeEqn调用中的“eqn”突出显示,并抛出以下编译错误。 Compile Error: ByRef

我很沮丧,因为我将一个字符串传递给一个调用字符串的函数,但编译器声称存在类型不匹配。我该怎么办?

2 个答案:

答案 0 :(得分:1)

确实存在问题,因为变量 eqn 在示例的第二行隐式声明为Variant类型:Dim eqn, name As String。在VBA中,你需要显式声明每个变量,即使它在同一行(除非它确实是Variant),如下所示:

Dim eqn As String, name As String

答案 1 :(得分:1)

在您的TrendLine子例程中,您已将eqn声明为Variant

Dim eqn, name As String

MakeEqn函数中,您希望收到(通过引用)String

Function MakeEqn(i As Integer, eqn As String) As String

您无法将Variant传递给ByRef String。 (它将生成“ByRef参数类型不匹配”错误。)

最简单的解决方法是在eqn中声明StringTrendLine,即

Dim eqn As String, name As String

或者,您可以传递变量ByVal,这会强制从Variant转换为String

Function MakeEqn(i As Integer, ByVal eqn As String) As String