Excel精英培训网

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

[已解决]批量打开一批工作簿,如何简化操作代码

[复制链接]
发表于 2016-9-11 13:49 | 显示全部楼层 |阅读模式
刚学VBA,我在工作簿1中批量循环打开一批工作簿,然后修改其中各个工作表中指定的单元格数据,这时我用了大量的activeworsheet代码例如
   If ActiveWorkbook.Sheets("1").Range("D112").Value = ActiveWorkbook.Sheets("1").Range("D81").Value / 2 Then
    ActiveWorkbook.Sheets("1").Range("D112").Value = ActiveWorkbook.Sheets("1").Range("D81").Value * 0.3 + 0.4
    Else: ActiveWorkbook.Sheets("1").Range("d81").Interior.ColorIndex = color
    ActiveWorkbook.Sheets("1").Range("T112").Value = "1"
    End If


ActiveWorkbook.Sheets("2").Range("O83").Value = "=D83*I83"
    ActiveWorkbook.Sheets("2").Range("O84").Value = "=D84*I84"
    ActiveWorkbook.Sheets("2").Range("O81").Value = "=D81*I81"
    ActiveWorkbook.Sheets("2").Range("O82").Value = "=D82*I82"


工作簿中的表格很多,请问我怎么能让代码简单点,不用输入那么多的ActiveWorkbook.Sheets?

请各位老师赐教,谢谢
最佳答案
2016-9-11 16:49
本帖最后由 zjdh 于 2016-9-11 16:51 编辑

或简化为
  With ActiveWorkbook.Sheets("1")
        If .Range("D112") = .Range("D81") / 2 Then
            .Range("D112") = .Range("D81") * 0.3 + 0.4
        Else: .Range("D81").Interior.ColorIndex = Color
            .Range("T112") = "1"
        End If
    End With
    With ActiveWorkbook.Sheets("2")
        For I = 81 To 84
            .Cells(I, "O") = "=D" & I & "*I" & I
        Next
    End With
发表于 2016-9-11 16:39 | 显示全部楼层
set wb=ActiveWorkbook.Sheets("1")
if wb.Range("D112")=wb.Range("D81")/2 then
………………
回复

使用道具 举报

发表于 2016-9-11 16:41 | 显示全部楼层
本帖最后由 zjdh 于 2016-9-11 16:42 编辑

你可以写成这样
    With ActiveWorkbook.Sheets("1")
        If .Range("D112").Value = .Range("D81").Value / 2 Then
            .Range("D112").Value = .Range("D81").Value * 0.3 + 0.4
        Else: .Range("d81").Interior.ColorIndex = Color
            .Range("T112").Value = "1"
        End If
    End With
    With ActiveWorkbook.Sheets("2")
        .Range("O83").Value = "=D83*I83"
        .Range("O84").Value = "=D84*I84"
        .Range("O81").Value = "=D81*I81"
        .Range("O82").Value = "=D82*I82"
    End With
回复

使用道具 举报

发表于 2016-9-11 16:49 | 显示全部楼层    本楼为最佳答案   
本帖最后由 zjdh 于 2016-9-11 16:51 编辑

或简化为
  With ActiveWorkbook.Sheets("1")
        If .Range("D112") = .Range("D81") / 2 Then
            .Range("D112") = .Range("D81") * 0.3 + 0.4
        Else: .Range("D81").Interior.ColorIndex = Color
            .Range("T112") = "1"
        End If
    End With
    With ActiveWorkbook.Sheets("2")
        For I = 81 To 84
            .Cells(I, "O") = "=D" & I & "*I" & I
        Next
    End With
回复

使用道具 举报

 楼主| 发表于 2016-9-11 22:25 | 显示全部楼层
多谢两位老师指点,可以少走弯路
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-3-28 22:17 , Processed in 0.308776 second(s), 11 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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