gpt4 book ai didi

vba - 在 VBA 中使用 "For"循环的问题

转载 作者:行者123 更新时间:2023-12-04 22:04:34 26 4
gpt4 key购买 nike

出于某种原因,我的代码无法正常工作。我收到“错误 91”。我用“对于每个循环,但这对我不起作用。

它告诉我调试

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

最佳答案

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循环迭代工作表索引,因此您可以分配 shtCurrentWorksheets 中的项目收藏:
Set shtCurrent = Worksheets(intCount)

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

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

关于vba - 在 VBA 中使用 "For"循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26726440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com