我想将一些数据单元从Workbook A导入到WorkBook B.我的工作是使用application.inputbbox来放置值。问题是我在输入框上单击取消。
此行发生运行时错误1004。
Set xRng1 = .Range(.Cells(addStartRow, 2), .Cells(addEndRow, 12))
我的问题是如何在没有错误弹出的情况下点击取消输入框。我所知道的是,可以通过放置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
答案 0 :(得分:3)
正如@Tim Williams在评论中所说,您需要做的就是在Input Box
上点击取消时处理变量会发生什么
将此添加到您的代码中
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