将值从一个工作表插入另一个工作表

时间:2014-12-31 20:52:14

标签: excel-vba vba excel

我在一张名为“数据存储”的表格中有数据。我想在另一张表中显示部分数据。代码的第一部分根据用户的输入找到数据,即RPName = Range ("Role Play")下一部分根据“角色扮演”确定一个范围,这是一系列将被平均的数字。

我在这一行收到错误:

Sheets("Data Storage").Range(Cells(RPName_rng1, 5), Cells(RPName_tot, 5)).Name = "Com1avg"

我无法弄清楚为什么会导致错误。

' average Macro
Dim RPName As String, RPName_rng1 As Integer, RPName_rng2 As Integer, RPName_tot As Integer
'get value from Role_Play cell
RPName = Range("Role_Play")
'    MsgBox ("Variable RPNam is selected in Macro average" & RPName)

' Find first instance of RPName
RPName_rng1 = Sheets("Data Storage").Cells.Find(What:=RPName, After:=Cells(1, 1), SearchOrder:=xlByRows).Row
'    MsgBox RPName_rng1

'Count number of RPname
RPName_rng2 = Application.WorksheetFunction.CountIf(Sheets("Data Storage").Range("A:A"), RPName)
'    MsgBox RPName_rng2
RPName_tot = RPName_rng1 + RPName_rng2 - 1
'    MsgBox RPName_tot

'Name range here
Sheets("Data Storage").Range(Cells(RPName_rng1, 5), Cells(RPName_tot, 5)).Name = "Com1avg"
Sheets("Data Storage").Range(Cells(RPName_rng1, 7), Cells(RPName_tot, 7)).Name = "Com2avg"
Sheets("Data Storage").Range(Cells(RPName_rng1, 9), Cells(RPName_tot, 9)).Name = "Com3avg"
Sheets("Data Storage").Range(Cells(RPName_rng1, 11), Cells(RPName_tot, 11)).Name = "Com4avg"
Sheets("Data Storage").Range(Cells(RPName_rng1, 13), Cells(RPName_tot, 13)).Name = "Com5avg"
Sheets("Data Storage").Range(Cells(RPName_rng1, 15), Cells(RPName_tot, 15)).Name = "Com6avg"
Sheets("Data Storage").Range(Cells(RPName_rng1, 17), Cells(RPName_tot, 17)).Name = "Com7avg"


'    Range("RPData").Select
    Application.CutCopyMode = False
    Range("CA_Com1").FormulaR1C1 = "=AVERAGE(Com1avg)"
    Range("CA_Com2").FormulaR1C1 = "=AVERAGE(Com2avg)"
    Range("CA_Com3").FormulaR1C1 = "=AVERAGE(Com3avg)"
    Range("CA_Com4").FormulaR1C1 = "=AVERAGE(Com4avg)"
    Range("CA_Com5").FormulaR1C1 = "=AVERAGE(Com5avg)"
    Range("CA_Com6").FormulaR1C1 = "=AVERAGE(Com6avg)"
    Range("CA_Com7").FormulaR1C1 = "=AVERAGE(Com7avg)"
'    Sheets("Data View").Activate
End Sub

1 个答案:

答案 0 :(得分:0)

您需要完全限定Cells的位置,否则默认为ActiveSheet。使用With块变得更容易(也更易读)。

With Sheets("Data Storage")
    .Range(.Cells(RPName_rng1, 5), .Cells(RPName_tot, 5)).Name = "Com1avg"
    ...
End With

请注意.Cells块中With的使用方式。完成此操作后,Cells范围将与With语句中定义的工作表相关。

如果你想在没有With阻止的情况下做同样的事情,你的电话会是这样的:

Sheets("Data Storage").Range(Sheets("Data Storage").Cells(RPName_rng1, 5), Sheets("Data Storage").Cells(RPName_tot, 5)).Name = "Com1avg"