VBA打开工作簿并将其分配给变量错误

时间:2018-01-20 16:36:50

标签: vba

我正在编写遍历文件的宏,并将符合某些条件的行标记为OK。从文件启动时一切正常。问题是,当我尝试从另一个工作簿启动它时,我不断收到此错误“运行时错误1004:选择方法或范围类失败”在行

范围( “C2”)。选择

我认为问题在于将打开的文件分配给变量mainFile。 (我可以浏览该文件,它会打开,我可以输入我想要的那一年然后崩溃) 你能告诉我我做错了吗?

    Sub sbVBA_To_Open_Workbook_FileDialog()

Dim strFileToOpen As Variant
Dim mainFile As Workbook

    strFileToOpen = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", MultiSelect:=False)

    If TypeName(strFileToOpen) = "String" Then
        Set mainFile = Workbooks.Open(strFileToOpen)
    Else
        MsgBox "No file selected."
        Exit Sub
    End If

'sub data works fine
Call data

With mainFile

'Everything below works fine when launched in the mainfile
Dim myYear As Date

myYear = InputBox("Choose year", "Choose year", 2018)

    Range("C2").Select

    Do Until ActiveCell.Value = ""

    If ActiveCell.Offset(0, 2) = "M" Then

        If ActiveCell.Offset(1, 2) = "C" Then

                If Day(ActiveCell.Value) = 1 Then

                                If Year(ActiveCell.Value) = myYear Then

                                    If Month(ActiveCell.Value) & Year(ActiveCell.Value) = Month(ActiveCell.Offset(1, 0).Value) & Year(ActiveCell.Offset(1, 0).Value) Then

                                    '^Comparing years and months

                                        If DateSerial(Year(ActiveCell.Offset(1, 0).Value), Month(ActiveCell.Offset(1, 0).Value + 1), 0) = ActiveCell.Offset(1, 0).Value Then
                                        ' ^End of month?

                                            ActiveCell.Offset(0, 10).Value = "OK"
                                        Else
                                        ActiveCell.Offset(0, 10).Value = "NOK"
                                        End If

                                    Else
                                    ActiveCell.Offset(0, 10).Value = "NOK"
                                    End If

                                Else
                                ActiveCell.Offset(0, 10).Value = "NOK"
                                End If

                Else
                ActiveCell.Offset(0, 10).Value = "NOK"
                End If
        Else
        ActiveCell.Offset(0, 10).Value = "NOK"
        End If
    Else
    ActiveCell.Offset(0, 10).Value = "NOK"
    End If

ActiveCell.Offset(1, 0).Select

Loop

End With

End Sub

1 个答案:

答案 0 :(得分:0)

仅仅因为您打开工作簿,它不会自动认为它是活动工作簿。

请在“With mainFile”行后尝试以下代码:

mainFile.Sheets([your desired sheet]).Activate

然后,在range.select部分之前,添加activesheet:

ActiveSheet.Range(“C2”).Select