我有一个宏用来从共享局域网中检索数据,但是,如果我想“取消”该功能,而不是加快命令的执行速度,我会在VBA窗口中得到一个错误,并且只会出现“结束”、“调试”或“帮助”选项。
我需要什么代码才能使“取消”按钮起作用?
当我按cancel时,我得到一个"Run-time error '1004':error
下面是我的代码:
Sub test()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim r, r2 As Range, myCol As String
Dim fd As Office.FileDialog
Dim txtFileName As String
Set ws1 = ThisWorkbook.Sheets(1)
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.csv"
.Filters.Add "All Files", "*.*"
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
Application.Workbooks.Open txtFileName
Set ws2 = ActiveWorkbook.Sheets(1)
ThisWorkbook.Activate
With CreateObject("VBScript.RegExp")
.Pattern = "^([a-z]|[a-h][a-z]|[a-i][a-v])$"
.IgnoreCase = True
Do
myCol = InputBox("Enter Column")
Loop While Not .test(myCol)
End With
With CreateObject("Scripting.Dictionary")
.comparemode = vbTextCompare
For Each r In ws1.Range(myCol & "37", ws1.Range(myCol & Rows.Count).End(xlUp))
If IsEmpty(r) = False Then
For Each r2 In ws2.Range("c2", ws2.Range("c" & Rows.Count).End(xlUp))
If r2.Value = r.Value Then
ws2.Cells(r2.Row, 2).Copy
ws1.Cells(r.Row, 3).PasteSpecial xlValues
Exit For
End If
Next r2
End If
Next r
End With
Set ws1 = Nothing: Set ws2 = Nothing
End Sub
发布于 2019-03-12 04:12:11
如果用户取消对文件的选择,您可以退出代码:
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
Else
Exit Sub
End If
https://stackoverflow.com/questions/55108202
复制相似问题