vba 我的脚本类型不匹配

vba type mismatch on my script

所以,我在 Word 文档的 VBA 脚本中发现类型不匹配,但是编辑器上没有任何行发出信号...你们中的任何人都可以给我提示吗它可能是什么?

Private Sub bt_run_Click()
'set months array
Dim months As Variable
months = Array("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")


With ThisDocument.Tables(0)

Do While .Rows.Count > 2
    .Rows(2).Delete
Loop


'Ask for year
Dim req As String
Dim yr As Integer
req = InputBox("Insere ano.")

If IsNumeric(req) Then
    yr = CInt(req)
Else
    MsgBox ("Erro")
    Return
End If


'get previous year last week
'TODO

'Now generate current year months
For i = 1 To 12
    'get number of mondays on the month (how many weeks belong here)
    Dim mondays As Integer
    mondays = MondaysOnMonth(i, yr)

    'now generate a line for each monday
    For k = 1 To mondays

        .Rows.Add

    Next k

Next i

'get next year first week
'TODO

End With


End Sub


Function MondaysOnMonth(ByVal month As Integer, ByVal year As Integer) As Integer
Dim mondays As Integer
mondays = 0

Dim d As Date
Dim dtStr As String
dtStr = "1/" & month & "/" & year

d = DateValue(dtStr)

Dim days As Integer
days = dhDaysInMonth(d)

For i = 1 To days

    dtStr = i & "/" & month & "/" & year
    d = DateValue(dtStr)
    Dim w As Integer
    w = Weekday(d, vbMonday)

    If w = 0 Then
        mondays = mondays + 1
    End If

Next i
MondaysOnMonth = mondays

End Function

Function dhDaysInMonth(Optional ByVal dtmDate As Date = 0) As Integer
' Return the number of days in the specified month.
If dtmDate = 0 Then
    ' Did the caller pass in a date? If not, use
    ' the current date.
    dtmDate = Date
End If
dhDaysInMonth = DateSerial(year(dtmDate), _
 month(dtmDate) + 1, 1) - _
 DateSerial(year(dtmDate), month(dtmDate), 1)
End Function

这几乎生成了多少行,因为在文档的唯一 table 中全年有星期一。

我对 Visual Basic for Applications 的所有这些东西都没有真正的经验,但我假设它是编译器无法执行的某种类型转换,但是,我真的看不出它可能是什么(而且编译器没有给我必要的帮助),那可能是什么?

根据我(有限)的经验,数组在 VBA 中的设置略有不同:

'set months array
Dim months(11) As String
months(0) = "Janeiro"
months(1) = "Fevereiro"
months(2) = "Março"
months(3) = "Abril"
months(4) = "Maio"
months(5) = "Junho"
months(6) = "Julho"
months(7) = "Agosto"
months(8) = "Setembro"
months(9) = "Outubro"
months(10) = "Novembro"
months(11) = "Dezembro"

此外,我无法解决 table 0,因此将其更改为 table 1,代码似乎可以执行。

With ThisDocument.Tables(1)

希望对您有所帮助!

数组函数 Returns 一个包含数组的 Variant!!! 昏暗的月份作为变体

你们太亲密了。

在您的原始代码中,您应该能够将 Variable 更改为 Variant 并且初始化将按您的预期进行。

我在这里 copy/pasted 你的数组初始化,换入 Variant,并编写了一个循环,通过将值打印到即时 Window(如果它还不可见,请按 Ctrl+G 查看):

Sub TestMonthArrayInitialization()

    Dim months As Variant
        months = Array("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")

    Dim i As Integer
        For i = 0 To 11
            Debug.Print months(i)
        Next i

End Sub