我是VBA的新手,我试图将book1,sheet2中的单元格A2的内容用作粘贴的目标表,而book1,sheet2中的单元格E2的内容用作粘贴的目标单元格。 这些单元格的内容可以更改。 我正在复制并粘贴book1,sheet1,cell(n15)的内容。 任何帮助是极大的赞赏。 当我按book1,sheet1上的enter键时,我得到运行时错误下标超出范围,当我进入调试时,它突出显示了这一行:
Workbooks(“ Book2.xlsx”)。Worksheets(“ WeekT.Value”)。Range(“ NameCel.value”)。PasteSpecial Paste:= xlPasteValue
````
Public Sub Book1()
Dim WeekT As Range
Dim NameCel As Range
Set WeekT = Workbooks("Book1.xlsm").Worksheets("Sheet2").Range("A2")
Set NameCel = Workbooks("Book1.xlsm").Worksheets("Sheet2").Range("E2")
End Sub
Private Sub Workbook_open()
Worksheets("Sheet2").Range("A2").Value = (Me.Week.Value + "T")
Worksheets("Sheet2").Range("C2").Value = (Me.Collegue_Name.Value)
Worksheets("Sheet1").Range("N15").Value = ("")
End Sub
Private Sub Week_change()
Worksheets("Sheet2").Range("A2").Value = (Me.Week.Value + "T")
End Sub
Private Sub Enter_Click()
Set WeekT = Workbooks("Book1.xlsm").Worksheets("Sheet2").Range("A2")
Set NameCel = Workbooks("Book1.xlsm").Worksheets("Sheet2").Range("E2")
Workbooks("Book1.xlsm").Worksheets("Sheet1").Range("N15").Copy
Workbooks.Open "F:\\Folder1\Book2.xlsx"
Workbooks("Book2.xlsx").Worksheets(WeekT).Range(NameCel).PasteSpecial Paste:=xlPasteValues
End Sub
``````
答案 0 :(得分:1)
在我看来,您的工作过于繁琐。要将单元格值复制到另一个值,只需编写:
Workbooks("destiny file").Sheets("sheet name").Cells(Row, Column).FormulaR1C1 = Workbooks("origin file").Sheets("sheet name").Cells(Row, Column).value
如果在工作簿和工作表中使用变量,它将“更流畅”:
----------
Dim W1 as Workbook
Set W1 = Workbooks("origin workbook")
Dim S1 as Worksheet
Set S1 = W1.Sheets("sheet name")
'---------
Dim W2 as Workbook
Set W2 = Workbooks("destiny workbook")
Dim S2 as Worksheet
Set S2 = W2.Sheets("sheet name")
'--> Copy the value:
S2.Cells(Row, Column).FormulaR1C1 = S1.Cells(Row, Column).value
通过这种方式,您不必使用Copy/Paste
命令。