修复循环中的不匹配错误

时间:2017-12-28 21:53:01

标签: vba excel-vba excel

继续上一个问题。我想我已经取得了一些进展但又被卡住了:

我创建了两个循环 - 一个月供用户检查。其他将保持隐藏但携带每个文件的位置。我希望从其他文件中选择值(每个文件中的“Training1”)并将其带到当前文件的“2017 Actuals”。

我测试了部分内容,我认为我在下面出错了,这给了我一个不匹配的错误,但任何提示都会有所帮助:

Set wks = wkb.Sheets("Training1")

完整代码:

Private Sub UpdateActuals_Click()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.AskToUpdateLinks = False
Dim p As Integer
Dim i As Integer
For i = 1 To 12
    If Me.Controls("Month" & i).Value = True Then
        For p = 1 To 12
        Dim wkb As Workbook
        Dim wks As Workbook
        Set wkb = Workbooks.Open(Me.Controls("Location" & p))
        Set wks = wkb.Sheets("Training1")
        ThisWorkbook.Sheets("2017 Actuals").Range(i + 1, 5) = wks.Range("Start:Finish")
        Next p
    End If
Next i

wkb.Close
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

您需要将wks声明为Worksheet类型。

因此,在您的代码块中,将其更新为:

If Me.Controls("Month" & i).Value = True Then
    For p = 1 To 12
    Dim wkb As Workbook
    Dim wks As Worksheet    ' Not Workbook
    Set wkb = Workbooks.Open(Me.Controls("Location" & p))
    Set wks = wkb.Sheets("Training1")
    ThisWorkbook.Sheets("2017 Actuals").Range(i + 1, 5) = wks.Range("Start:Finish")
    Next p
End If