忽略运行时错误1004
我想从工作簿A中导入一些数据单元格到WorkBook B.我所做的是我使用了application.inputbbox来放置这个值。 问题是当我点击取消input框。
运行时错误1004发生在这一行上。
Set xRng1 = .Range(.Cells(addStartRow, 2), .Cells(addEndRow, 12))
我的问题是我怎样才能点击取消input框没有错误popup窗口。 我所知道的是,可以通过提出on error
陈述来完成。 我不知道把声明放在哪里
这是我的代码。
Private Sub importbr_Click() Dim xWb As Workbook Dim xAddWb As Workbook Dim xRng1 As Range Dim xRng2 As Range Set xWb = Application.ActiveWorkbook Dim xTitleId As String Dim addStartRow As Integer Dim addEndRow As Integer Dim pastevalue As Integer xTitleId = "Select BR file" With Application.FileDialog(msoFileDialogOpen) .InitialFileName = "C:\New" .Filters.Clear .Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa" .AllowMultiSelect = False .Show If .SelectedItems.Count > 0 Then Application.Workbooks.Open .SelectedItems(1) Set xAddWb = Application.ActiveWorkbook addStartRow = Application.InputBox(prompt:="Type Start row", Title:=xTitleId, Default:="200", Type:=1) addEndRow = Application.InputBox(prompt:="Type End row", Title:=xTitleId, Default:="500", Type:=1) With xAddWb.Sheets(1) 'change the index as needed Set xRng1 = .Range(.Cells(addStartRow, 2), .Cells(addEndRow, 12)) End With xWb.Activate Set xRng2 = Cells(5, 1) xRng1.Copy xRng2 xAddWb.Close False End If End With End Sub
正如@Tim Williams在评论中所说,你所要做的就是当你在Input Box
上点击取消时,处理variables的变化
将此添加到您的代码中,
If addStartRow > 0 And addEndRow > 0 Then Set xRng1 = .Range(.Cells(addStartRow, 2), .Cells(addEndRow, 12)) Else GoTo eExit End If
而完整的代码,
Dim xWb As Workbook Dim xAddWb As Workbook Dim xRng1 As Range Dim xRng2 As Range Set xWb = Application.ActiveWorkbook Dim xTitleId As String Dim addStartRow As Integer Dim addEndRow As Integer Dim pastevalue As Integer xTitleId = "Select BR file" With Application.FileDialog(msoFileDialogOpen) .InitialFileName = "C:\New" .Filters.Clear .Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa" .AllowMultiSelect = False .Show If .SelectedItems.Count > 0 Then Application.Workbooks.Open .SelectedItems(1) Set xAddWb = Application.ActiveWorkbook addStartRow = Application.InputBox(Prompt:="Type Start row", Title:=xTitleId, Default:="200", Type:=1) addEndRow = Application.InputBox(Prompt:="Type End row", Title:=xTitleId, Default:="500", Type:=1) If addStartRow > 0 And addEndRow > 0 Then With xAddWb.Sheets(1) 'change the index as needed Set xRng1 = .Range(.Cells(addStartRow, 2), .Cells(addEndRow, 12)) End With xWb.Activate Set xRng2 = Cells(5, 1) xRng1.Copy xRng2 End If xAddWb.Close False End If End With