Worksheet_Change如果不是按照范围内的列表那么不行

时间:2018-02-22 09:28:42

标签: vba

想知道代码是否为空白&如果不是按照列表(在A:A范围内),那么就不要做任何事情。如果在列表中找到Workbooks.Open。在这种情况下,任何人都可以用正确的代码指导我。

我目前的代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "D11" Then

Workbooks.Open Filename:=ThisWorkbook.Worksheets("sheet1").Range("E11").Value, ReadOnly:=False, Password:=""

End If

End Sub

1 个答案:

答案 0 :(得分:0)

你可以使用试图打开某个工作簿并返回的hedper函数:

  • False如果不成功

  • True如果与有效Workbook对象参考一起成功

如下:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim wb As Workbook

    If Target.Address = "$D$11" Then

        If GetWorkBook(ThisWorkbook.Worksheets("sheet1").Range("E11").Value, wb) Then
            With wb 'reference just opened workbook

                ' your code to exploit opened workbook

            End With
        End If

    End If

End Sub

Function GetWorkBook(fullname As Variant, wb As Workbook) As Boolean
    On Error Resume Next 'avoid subsequent error stop the function
    Set wb = Workbooks.Open(Filename:=fullname, ReadOnly:=False, Password:="") 'try and open a workbook with passed full name
    GetWorkBook = Not wb Is Nothing 'return function result (i.e. 'True' if 'wb is a valid 'Workbook' reference)
End Function