循环遍历所有活动的工作表

时间:2015-07-01 09:28:31

标签: excel vba loops

我在使用VBA方面经验非常薄弱,但现在遇到了真正需要的问题。

我需要将多个工作表中的单元格值(除了"摘要")复制到一个工作表中,但面临问题。运行宏时,我使用我需要的值获得大约30行,但所有30个值都属于同一个工作表。好像循环只运行了大约1个工作表。你能帮我找一下代码中的错误吗?

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Test
    public void test1() {
        //save new user in db:
        userDao.save(new User("Name1")); //in result in db 1 user
        //set savepoint:
        TransactionStatus status = platformTransactionManager.getTransaction(
                new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
        //do changes in db:
        userDao.save(new User("Name2")); //in result in db 2 users
        //roll back to savepoint:
        platformTransactionManager.rollback(status);
        userDao.findAll(); //in result in db 1 user
    }

2 个答案:

答案 0 :(得分:0)

使用Cells时(Rows.Count,7).End(xlUp)。选择和其他所有内容,它们引用当前工作表。所以你要么把它们放在它们前面Worksheet.Cells(Rows.Count,7).End(xlUp)。选择或者你首先使用Worksheet.Activate激活工作表

或者你可以这样做:

private int level;    
public void setLevel(int level, Context context){
    Utils.saveSharedPreferences(context, "level", level+"");
    this.level = level;
}

public int getLevel(Context context){
    level = Utils.stringToInt(Utils.readSharedPreferences(context, "level"));
    return level;
}

答案 1 :(得分:0)

试试这个:

Sub CopyTotalSalesPrice()

For Each Worksheet In ActiveWorkbook.Worksheets
    If Worksheet.Name <> "Summary" Then
      Worksheet.Select
      Worksheet.Cells(Worksheet.Rows.Count, 7).End(xlUp).Select
    End If
    If Selection.Value > "0" Then
      Selection.Copy
      Worksheets("Summary").Cells(Worksheet.Rows.Count, 6).End(xlUp).Offset(2, 0).PasteSpecial (xlPasteValues)

      Range("D4").Select
      Selection.Copy
      Worksheets("Summary").Cells(Worksheet.Rows.Count, 4).End(xlUp).Offset(2, 0).PasteSpecial (xlPasteValues)

    End If

Next Worksheet

Worksheets("Summary").Select
End Sub

我将此Cells(Rows.Count, 7).End(xlUp).Select替换为Worksheet.Cells(Worksheet.Rows.Count, 7).End(xlUp).Select