我的脚本上的vba类型不匹配

时间:2015-01-05 23:15:16

标签: vba ms-word type-mismatch

所以,我在Word文档的VBA脚本中出现了类型不匹配,但是编辑器上没有任何行标志......你们中的任何人都可以给我一些暗示吗?< / p>

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

这几乎产生了与文件唯一表格中全年的星期一相同的行数。

我在Visual Basic for Applications的所有这些方面都没有经验,但我认为它是某种类型的转换,编译器无法执行,但是,我无法真正看到它可能是什么(和编译器没有给我必要的帮助),那可能是什么?

3 个答案:

答案 0 :(得分:0)

在我的(有限)经验中,数组在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"

另外,我无法解决表0问题,因此将其更改为表1并且代码似乎已执行。

With ThisDocument.Tables(1)

希望这有帮助!

答案 1 :(得分:0)

数组函数 返回包含数组的Variant! 昏暗的月份作为变体

答案 2 :(得分:0)

你太近了。

在原始代码中,您应该能够将Variable更改为Variant,初始化将按预期工作。

这里我复制/粘贴了你的数组初始化,交换了Variant,写了一个循环,通过将值打印到立即窗口来确认数组已正确初始化(按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