Range.Copy与用户估算的变量

时间:2019-06-17 19:04:53

标签: excel vba

仅尝试将一部分数据从一个工作簿复制到另一工作簿,以避免必须使用间接引用。复制的区域需要可变。 Index和Index2是A1 D77样式。运行以下内容,我得到“范围类的复制方法失败。”我怎么了?

Dim directory As String, fileName As String, index As String, index2 As 
String

directory = TextBox2
fileName = TextBox1
index = TextBox4
index2 = TextBox5

Workbooks.Open (directory & fileName)

Workbooks(fileName).Worksheets("Sheet1").Range(index & ":" & index2).Copy _
    Workbooks("Copy of Worksheet Template for Monthly 
    report.xlsm").Worksheets("Data")

Workbooks(fileName).Close
fileName = Dir()

Worksheets("Tables").Select

2 个答案:

答案 0 :(得分:0)

您需要发送范围地址

Dim DataRng As Range
Set DataRng = Range(index, index2)
DataRng.Select

Workbooks(fileName).Worksheets("Sheet1").Range(DataRng.Address).Copy _
Workbooks("Copy of Worksheet Template for Monthly 
report.xlsm").Worksheets("Data")

此外,仅当您说indexindex2时,才应将stringA1指定为D77,否则应使用{{ 1}}或integers,如果您仅使用数字,则可以使用longindex = cells(row,col)

指定范围

答案 1 :(得分:0)

弄清楚了。     私人子CommandButton1_Click()

Dim directory As String, fileName As String, index As String, index2 As String, 
DataRNG As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

directory = TextBox2
fileName = TextBox1
index = TextBox4
index2 = TextBox5
DataRNG = index & ":" & index2


Workbooks.Open (directory & fileName)

Workbooks(fileName).Worksheets("Sheet1").Range(DataRNG).Copy _
    Workbooks("Monthly Service and Parts Report.xlsm").Worksheets("Data").Range("A1")

Workbooks(fileName).Close

Worksheets("Tables").Select

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub