我经历了很多论坛,但仍然不明白我要去哪里。我第一次尝试VBA代码。
Private Sub Refresh_Click()
Dim ws As Long
Dim lRow As Variant
Dim wb As Workbook
Dim Arr() As Variant
Dim DHSWMP As String
Dim Dams As String
Dim PotR As String
DHSWMP = "E:\Copy of PWC DHSWMP WorkSheets.xlsm"
'Dams = "x"
'PotR = "x"
Application.ScreenUpdating = False
Set wb = Workbooks.Open(DHSWMP, True, False)
wb.Activate
ws = Worksheets.Count
Do While ws > 0
wb.Sheets(ws).Activate
lRow = Cells(Rows.Count, 2).End(xlUp).Row
MsgBox (lRow)
代码可以通过,但是它在运行宏的“母版”而不是打开的工作簿上执行lRow。确实让我感到困惑的是,代码确实在打开的工作簿上执行worksheets.count。
欢呼
答案 0 :(得分:0)
您的代码按我的预期运行。这是为什么您应该完全限定参考文献的完美示例。
要测试正在发生的事情:
ScreenUpdating
MsgBox
Immediate Window
进行其他测试MsgBox Cells(Rows.Count, 2).End(xlUp).Address & vbNewLine & Cells(Rows.Count, 2).End(xlUp).Parent.Name & vbNewLine & Cells(Rows.Count, 2).End(xlUp).Parent.Parent.Name
您应避免在迭代时使用Do
和While
循环;如果您同时知道开始和结束。 For
和For Each
循环wi
这里有两种不同的代码编写方式。注意,使用With
语句和限定引用。例如,Cells
和Rows
都符合Worksheet
中.Cells(.Rows.Count, 2).End(xlUp).Row
的条件。这对于避免对代码的实际目标造成任何混淆非常重要。
Private Sub Refresh_Click()
Application.ScreenUpdating = False
Dim ws As Worksheet, wbDHSWMP As Workbook
Dim lRow As Variant
Dim Arr() As Variant
Dim DHSWMP As String, Dams As String, PotR As String
DHSWMP = "C:\Copy of PWC DHSWMP WorkSheets.xlsm"
Set wbDHSWMP = Workbooks.Open(DHSWMP, True, False)
For Each ws In wbDHSWMP.Worksheets
With ws
lRow = .Cells(.Rows.Count, 2).End(xlUp).Row
MsgBox (lRow)
End With
Next
Application.ScreenUpdating = True
End Sub
Private Sub Refresh_Click()
Application.ScreenUpdating = False
Dim wbDHSWMP As Workbook
Dim lRow As Variant, n As Long
Dim Arr() As Variant
Dim DHSWMP As String, Dams As String, PotR As String
DHSWMP = "C:\Copy of PWC DHSWMP WorkSheets.xlsm"
Set wbDHSWMP = Workbooks.Open(DHSWMP, True, False)
For n = wbDHSWMP.Worksheets.Count To 1 Step -1
With wbDHSWMP.Worksheets(n)
lRow = .Cells(.Rows.Count, 2).End(xlUp).Row
MsgBox (lRow)
End With
Next
Application.ScreenUpdating = True
End Sub