Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 2930|回复: 14

[已解决]求助:我要在这个宏里面任意增加多个累计怎么改

[复制链接]
发表于 2012-12-12 14:00 | 显示全部楼层 |阅读模式
本帖最后由 286227370 于 2012-12-12 17:13 编辑

Sub sheet1(sheet1)
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then
Cells(2, 1) = Cells(2, 1) + Cells(1, 1)
End If
End Sub
这个宏里面只有一个累计,就是$A$1,我要继续增加几个累计怎么做。
最佳答案
2012-12-12 15:31
  1. Private Sub Worksheet_Change(ByVal Target As Range)
  2.     Application.EnableEvents = False    '关闭事件
  3.    
  4.     If Target.Count = 1 Then    '判断修改区域的数量
  5.         If Not Intersect(Target, Range("a1:g1")) Is Nothing Then    '判断是否在A1:G1
  6.             If IsNumeric(Target) And IsNumeric(Target.Offset(1)) Then   '判断是不是数值
  7.                 Target.Offset(1) = Target.Offset(1) + Target    '累加
  8.             End If
  9.         End If
  10.     End If
  11.     Application.EnableEvents = True
  12. End Sub
复制代码
发表于 2012-12-12 14:24 | 显示全部楼层
Cells(3, 1) = Cells(3, 1) + Cells(1, 1)
照着代码改就成了。
回复

使用道具 举报

 楼主| 发表于 2012-12-12 14:28 | 显示全部楼层
hwc2ycy 发表于 2012-12-12 14:24
Cells(3, 1) = Cells(3, 1) + Cells(1, 1)
照着代码改就成了。

这样只有在A列可以,要在其它列怎么改,但要保留A列的数据
回复

使用道具 举报

发表于 2012-12-12 14:29 | 显示全部楼层
cells(3,1),1代到A列,2就代表B列,以此类推。
回复

使用道具 举报

发表于 2012-12-12 14:29 | 显示全部楼层
第1个参数是行,第2个参数是列。
回复

使用道具 举报

发表于 2012-12-12 14:35 | 显示全部楼层
If Target.Address = "$A$1" Then   你这行限制了只能是a1

你这个宏有几点不对   一是如果用事件脚本的话第一行就不需要sub xxxx()了
二 没有加上 Application.EnableEvents = False  你原来这个代码会无限循环,因为触发事件本身就改动了表格,又引起触发.
三 cells(x,y)的值求和的话应该加上.value

重写如下:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Row > 6 Then Exit Sub
If Target.Column > 5 Then Exit Sub
Application.EnableEvents = False
Cells(2, 1).Value = Cells(2, 1).Value + Target.Value
Application.EnableEvents = True
End Sub

我这个的条件就改成了如果行数大于6,或者列数大于5,都不触发  你可以自己修改
回复

使用道具 举报

发表于 2012-12-12 14:37 | 显示全部楼层
楼上的分析得对。
回复

使用道具 举报

 楼主| 发表于 2012-12-12 14:41 | 显示全部楼层
hwc2ycy 发表于 2012-12-12 14:29
第1个参数是行,第2个参数是列。

我要保留$A$1,而在其它列里面同样计算怎么加
回复

使用道具 举报

发表于 2012-12-12 14:42 | 显示全部楼层
怎么计算?是累加A1吗?
回复

使用道具 举报

 楼主| 发表于 2012-12-12 14:45 | 显示全部楼层
hwc2ycy 发表于 2012-12-12 14:42
怎么计算?是累加A1吗?

不是,是多个计算。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-4-27 02:48 , Processed in 0.487110 second(s), 10 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表