0

我修改了 youtube 教程中的代码(https://www.youtube.com/watch?v=h_sC6Uwtwxk,谢谢)以从其他 excel 文件中导入数据。

Sub get_data_from_source_file()

Dim FileToOpen As Variant
Dim SrcWB As Workbook
Dim SrcWS As Worksheet
Dim SrcRng As String
Let SrcRng = "A2:I501"
Dim DesWB As Workbook
Dim DesWS As Worksheet
Set DesWS = Worksheets("MAIN")
Dim DesLR As Long
DesLR = Application.WorksheetFunction.CountA(DesWS.Range("A1:A50001"))
Dim DesRng As String  
Let DesRng = "A" & DesLR + 1 & ":" & "I" & DesLR + 500
Dim sFileName As String

Application.ScreenUpdating = False

FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", filefilter:="Excel Files (*.xlsx;.*.csv*),*xlsx;csv*")
If FileToOpen <> False Then
On Error GoTo WrongPWD
Set SrcWB = Application.Workbooks.Open(FileToOpen)
ThisWorkbook.Worksheets("MAIN").Range(DesRng) = SrcWB.Sheets(1).Range(SrcRng).Value
SrcWB.Close False
MsgBox "Data import was successful."
End If

密码错误:

        If Err.Number = 1004 Then

        Dim MsgPrompt As String
        MsgPrompt = "The file could not be opened. Try again?"
        Select Case MsgBox(prompt:=MsgPrompt, Buttons:=vbYesNoCancel, Title:="Decision")
        Case Is = vbYes: 'Do nothing and let the code loop
        Case Is = vbNo: Exit Sub
        Case Else: Exit Sub 'User canceled (includes VbCancel and pressing the x top right corner)
        End Select


        Exit Sub

        End If

Application.ScreenUpdating = True

End Sub

代码工作正常。但是,我的源文件可能以某种方式受密码保护。当我输入错误的密码时,代码终止。请告知我处理此错误的代码,例如提示 msgbox,通知用户再次运行命令并退出 sub 等?

4

1 回答 1

0

这是一个如何做到这一点的示例:

Dim wb As Workbook

Do While wb Is Nothing
    On Error Resume Next
        Set wb = Workbooks.Open(FilePath)
    On Error GoTo 0
    If wb Is Nothing Then
        Dim MsgPrompt As String
        MsgPrompt = "The file could not be opened. Try again?"
        Select Case MsgBox(prompt:=MsgPrompt, Buttons:=vbYesNoCancel, Title:="Decision")
            Case Is = vbYes: 'Do nothing and let the code loop
            Case Is = vbNo: Exit Sub
            Case Else: Exit Sub 'User canceled (includes VbCancel and pressing the x top right corner)
        End Select
    End If
Loop
于 2020-03-20T00:56:03.473 回答