【发布时间】:2016-08-19 03:10:09
【问题描述】:
我一直在寻找答案,但找不到合适的答案。
我有一个两页的 Excel 电子表格,我希望在其中添加一个 VBA 宏。第二张表的第 1 列有许多技能,第 2 到 13 列有这些技能的“分数”,每列代表一个月。表 1 有一个表格,其中从下拉列表中选择以下内容:被评分的技能、该人最后一次评估的月份和该人正在接受评估的月份。我已设法显示正在评估的技能的相关“上个月”分数,但现在希望将所有技能的分数从该月的列复制到代表该人正在接受评估的月份的列中。然后,我将用新数据覆盖特定的技能分数。 这是我迄今为止尝试过的......
With Worksheets("Sheet2")
Range(Cells(2,Sheet1!D17),Cells(Sheet1!D19,Sheet1!D17).Copy Range(Cells(2,Sheet1!D20),Cells(Sheet1!D19,Sheet1!D20)
End With
其中D17包含要复制的列的列号,D19包含计算出来的该列的最后一行,D20包含需要粘贴数据的列的列号。我尝试使用 Sheet2 上的单元格来包含这些值,以防引用 Sheet1 时出现问题但遇到同样的问题。如果我用数字替换变量,它会起作用。
这似乎是在 Cells() 构造中使用变量的问题。请大家指点一下?
我已经尝试了以下方法:
With Worksheets("Sheet1")
oldMonthCol = Range("D17").Value
newMonthCol = Range("D20").Value
lastRow = Range("D19").Value
End With
这些变量在此代码块之前被定义为 Long。然后在前面给出的表达式中使用它们来替换 Sheet1!D17 等。代码可以编译,但是当我查看 oldMonthCol 等的值时,它应该是非零数字时为 0。请问有什么想法吗?
刚刚发现它正在修改 Sheet1,尽管将 Worksheets 设置为 Sheet2...
使用以下方法解决了这个问题:
With Worksheets("Sheet2").Select
Range(Cells(2,oldMonthCol),Cells(lastRow,oldMonthCol).Copy Range(Cells(2,newMonthCol),Cells(lastRow,newMonthCol)
End With
这仅适用于我在单元格中输入的值,而不是公式的结果。
解决了! 子Button2_Click()
Dim skillName As String
Dim newScore As Long
Dim skillNameRow As Long
Dim oldMonth As String
Dim newMonth As String
Dim oldMonthCol As Integer
Dim newMonthCol As Integer
Dim lastRow As Integer
Dim oldMonthCol2 As Integer
Dim newMonthCol2 As Integer
Dim lastRow2 As Integer
Dim skillNameRow2 As Integer
Dim newSkillValue As Integer
With Worksheets("Sheet1")
skillName = Range("D3").Value
skillNameRow = Range("D16").Value
skillNameRow2 = skillNameRow + 1
oldMonth = Range("G3").Value
newMonth = Range("G5").Value
oldMonthCol = Range("F17").Value
oldMonthCol2 = oldMonthCol + 1
newMonthCol = Range("F20").Value
newMonthCol2 = newMonthCol + 1
lastRow = Range("F19").Value
lastRow2 = lastRow + 1
newSkillValue = Range("F21").Value
End With
With Worksheets("Sheet2").Select
Range(Cells(2, oldMonthCol2), Cells(lastRow, oldMonthCol2)).Copy Range(Cells(2, newMonthCol2), Cells(lastRow, newMonthCol2))
Worksheets("Sheet2").Activate
Cells(skillNameRow2, newMonthCol2).Select
ActiveCell.Value = newSkillValue
End With
End Sub
不优雅,但它有效。有一些变量尚未使用,但它们是为将来的添加而设计的......
【问题讨论】:
-
欢迎来到 SO。到目前为止,您尝试了什么,是什么导致了问题?我鼓励您阅读以下帖子:How do I ask a good question.
-
请编辑您的帖子,而不是在 cmets 中发布长代码。
-
很抱歉违反了礼仪。我现在在问题中添加了文本和代码段。谢谢你对我的耐心。问候。
-
在您的
With块内,您需要限定像.Range("D17").Value这样的范围,否则它假定 ActiveSheet 上的范围可能不是 Sheet1。