如何使用两本工作簿及其工作表

时间:2017-12-08 22:53:26

标签: excel vba excel-vba worksheet

我一次使用两本工作簿。第一个工作簿是当前工作簿,第二个工作簿将在编程执行时打开。我已经制作了工作簿和工作表的全局对象。我在同时使用工作表方面遇到了问题。错误是ERROR: object variable or with block variable, not set。我在第二个子例程中提到了注释中的错误。

Dim WB As Workbook
Dim WB2 As Workbook

Dim WKS As Worksheet
Dim WKS2 As Worksheet

Sub Button1_Click()
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    Set WB = ThisWorkbook
    WB.Activate

    fd.AllowMultiSelect = False
    fd.Title = "Provide a title here."
    fd.InitialFileName = ThisWorkbook.Path
    If fd.Show() = True Then
        strFile = fd.SelectedItems(1)
        Set WB2 = Workbooks.Open(strFile)
        Set WSK2 = WB2.Sheets("Schweitzer Analysis")
        CalculateGrades
    Else
        MsgBox ("No file selected")
    End If
End Sub

Sub CalculateGrades()
    ' first clear the contents where grades results can appear
    clearGradesContents

    Dim index As Integer ' for current sheet
    Dim index2 As Integer ' for student sheet
    Dim countCorrect As Integer ' to count no of correct answers

    index = 2
    index = 8
    countCorrect = 0

    ' this first error here
    ' ERROR: object variable or with block variable not set
    Set WKS = WB.ActiveSheet

    Do While index <= 21
        ' the SECOND error shows here
        If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then
            Count = Count + 1
        Else
            WKS.Cells(index, 5) = WKS2.Cells(index2, 3)
        End If

        If WKS.Cells(index, 3) = WKS2.Cells(index2, 4) Then
            Count = Count + 1
        Else
            WKS.Cells(index, 6) = WKS2.Cells(index2, 4)
        End If

        index2 = index2 + 1
        index = index + 1
    Loop

End Sub


Sub clearGradesContents()
    Range("E2:F21").Select
    Selection.ClearContents
    Range("I2:I3").Select
    Selection.ClearContents
End Sub

1 个答案:

答案 0 :(得分:0)

编辑:对于之前的回答感到抱歉,我没有看到你的全球声明,我确信这是因为你没有宣布它。

我认为问题如下:

[...]
Set WB = ThisWorkbook
WB.Activate '<-- WB is the active workbook now
[...]
Set WB2 = Workbooks.Open(strFile) '<-- WB2 is the active workbook now!
Set WSK2 = WB2.Sheets("Schweitzer Analysis")
CalculateGrades '<-- going to next macro
[...]
Set WKS = WB.ActiveSheet '<-- ERROR: WB2 is the active workbook. WB can't have an active sheet if it's not the active workbook

当然,如果WKS未正确设置,则无法执行此操作:

If WKS.Cells(index, 2) = WKS2.Cells(index2, 3) Then

我现在无法测试它,但我认为这应该是问题所在。 要解决它,

如果您确实需要WKS作为ActiveSheet

Dim activeSheetName As String
...
Sub Button1Click()
    ...
    Set WB = ThisWorkbook
    WB.Activate
    activeSheetName = WB.ActiveSheet.Name
    ...
End Sub
Sub CalculateGrades()
    ...
    Set WKS = WB.Sheets(activeSheetName)
    ...

如果您已经知道所需工作表的名称

只需写下:

Set WKS = WB.Sheets("your sheet")

而不是

Set WKS = WB.ActiveSheet