由于某些原因,我的代码无效。我得到"错误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
答案 0 :(得分:3)
shtCurrent
是Worksheet
个对象。尝试将其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