我正在尝试编写一些代码,以便将大量用户选择的数据从一个打开的工作簿传输到另一个工作簿。行/列的数量会有所不同,目标工作簿中的起点也会有所不同。 我在最后一行代码中得到调试运行时错误'13':输入不匹配。可能有一种更优雅的方式来做一些事情,比如调整目标范围,但其他一切似乎都按预期工作。
Public SourceWorkbook As Workbook
Public SourceWorksheet As Worksheet
Public DestWorkbook As Workbook
Public DestWorksheet As Worksheet
Public selectedRange As Range
Public selectedRows As Long
Public selectedColumns As Long
Sub SelectRange()
Set SourceWorkbook = ActiveWorkbook
Set SourceWorksheet = ActiveSheet
'Display the Input Box to make selection
On Error Resume Next
Set selectedRange = Application.InputBox( _
Prompt:="Select the range of cells you want to copy.", _
title:="Select Range", _
Default:=ActiveCell.Address, _
Type:=8)
' Was the Input Box canceled?
If selectedRange Is Nothing Then
MsgBox "Cancelled"
Exit Sub
End If
selectedRange.Select
'Set row and column number variables
selectedRows = Selection.Rows.Count
selectedColumns = Selection.Columns.Count
'vbModeless Form that allows user to select another open workbook and start cell. The OK button simply calls the MoveData sub.
SwitchWorkbooksForm.Show vbModeless
End Sub
Sub MoveData()
Dim DestRange As Range
Set DestWorkbook = ActiveWorkbook
Set DestWorksheet = ActiveSheet
'Start the desination range at the user select cell and Set it to the same size as the originally selected range
StartRow = ActiveCell.Row
finalRow = StartRow + selectedRows - 1
StartColumn = ActiveCell.Column
finalColumn = StartColumn + selectedColumns - 1
Range(Cells(StartRow, StartColumn), Cells(finalRow, finalColumn)).Select
Set DestRange = Selection
'Debug error on the next line
Workbooks(DestWorkbook).Worksheets(DestWorksheet).Range(DestRange).Value = _
Workbooks(SourceWorkbook).Worksheets(SourceWorksheet).Range(selectedRange).Value
End Sub
答案 0 :(得分:0)
您通过传入工作簿和工作表对象来使用Workbooks(...)
和Worksheets(...)
集合。您应该传递名称或使用您直接分配的工作簿和工作表参考。
Workbooks(DestWorkbook.name).Worksheets(DestWorksheet.name).Range(DestRange.address).Value = _
Workbooks(SourceWorkbook.name).Worksheets(SourceWorksheet.name).Range(selectedRange.address).Value
......或,
DestRange = selectedRange.Value
您不必继续重新定义您拥有Set
范围对象的父级。