激活已关闭的工作簿,执行lRow VBA

时间:2018-06-28 00:24:22

标签: excel vba excel-vba

我经历了很多论坛,但仍然不明白我要去哪里。我第一次尝试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。

欢呼

1 个答案:

答案 0 :(得分:0)

您的代码按我的预期运行。这是为什么您应该完全限定参考文献的完美示例。

要测试正在发生的事情:

  • 请勿关闭ScreenUpdating
  • 改善您的MsgBox
  • 使用F8浏览代码
  • 使用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
  • Cells.Parent.Name:返回工作表的名称
  • Cells.Parent.Name:返回工作簿的名称

enter image description here

您应避免在迭代时使用DoWhile循环;如果您同时知道开始和结束。 ForFor Each循环wi

这里有两种不同的代码编写方式。注意,使用With语句和限定引用。例如,CellsRows都符合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