在VBA中使用“For”循环问题

时间:2014-11-04 01:46:04

标签: vba excel-vba excel

由于某些原因,我的代码无效。我得到"错误91"。我用#34运行它很好;对于每个循环,但这对我不起作用。

它告诉我在

进行调试
strPrint = MsgBox(prompt:="Print " & shtCurrent & "?", Buttons:=vbYesNo + vbExclamation)

但我发现它没有任何问题。

Public Sub PrintWorksheets2()

    'declare variables and assign address
    Dim strPrint As String, intCount As Integer, wkbHours As Workbook, shtCurrent As Worksheet
    Dim intSum As Integer, shtCount As Integer
    Set wkbHours = Application.Workbooks("auco6215_HW10_Ex9.xlsm")

    shtCount = wkbHours.Sheets.Count
    intSum = 0

    'ask user if he or she wants to print the worksheet
    For intCount = 1 To shtCount
        'shtCurrent = wkbHours
        intSum = intSum + intCount
        strPrint = MsgBox(prompt:="Print " & shtCurrent & "?", Buttons:=vbYesNo + vbExclamation)
        If strPrint = vbYes Then        'if user wants to print
            shtCurrent.PrintPreview
        End If
    Next intCount

End Sub

2 个答案:

答案 0 :(得分:3)

shtCurrentWorksheet个对象。尝试将其Name属性(String)连接到您的msgbox提示符中:

strPrint = MsgBox(prompt:="Print " & shtCurrent.Name & "?", Buttons:=vbYesNo + vbExclamation)

现在strPrint被声明为String

Dim strPrint As String

并且MsgBox将返回vbMsgBoxResult枚举值 - 您在此处使VBA执行大量无用的隐式类型转换,为什么不将其声明为它返回的类型?

Dim strPrint As vbMsgBoxResult

现在你明白了为str添加前缀为变量名(也就是匈牙利符号)的原因很糟糕。


仅解决部分问题。当您有For Each循环时,每次迭代都会为表示当前迭代工作表的对象变量赋值。在带有For循环的代码中,您有一个shtCurrent工作表对象,但未分配;你正在递增一个柜台,但这就是你所做的一切。正如评论中暗示的那样,你还需要Set循环中shtCurrent对象的引用,之前你使用它 - 否则你的代码会爆炸"对象变量未设置"错误。

您的For循环会迭代工作表索引,因此您可以将shtCurrent分配给Worksheets集合中的项目:

Set shtCurrent = Worksheets(intCount)

For循环体内的任何其他内容之前执行此操作,您应该很高兴。

现在这一切都很好,但是当你重复对象时,使用For Each循环而不是For循环通常会更好。 For循环适用于迭代数组; For Each循环适用于迭代集合 - 我在这里使用For Each循环。

答案 1 :(得分:0)

请试一试。

'declare variables and assign address
Dim strPrint As String, intCount As Integer, wkbHours As Workbook, shtCurrent As Worksheet
Dim intSum As Integer, shtCount As Integer
Dim oResult
Set wkbHours = Application.Workbooks("auco6215_HW10_Ex9.xlsm")

shtCount = wkbHours.Sheets.Count
intSum = 0

'ask user if he or she wants to print the worksheet
For intCount = 1 To shtCount
    'shtCurrent = wkbHours
    intSum = intSum + intCount
    oResult = MsgBox(prompt:="Print " & shtCurrent & "?", Buttons:=vbYesNo + vbExclamation)
    If oResult = vbYes Then        'if user wants to print
        shtCurrent.PrintPreview
    End If
Next intCount