vba 尝试在所有 Excel 工作表上运行代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10288400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to run a code on all Excel sheets
提问by Nupur
I am trying to run this code on all worksheets that I have in one excel file but this is not working. It only merges cells on first sheet. Here is my code:
我正在尝试在一个 excel 文件中的所有工作表上运行此代码,但这不起作用。它只合并第一张纸上的单元格。这是我的代码:
Sub MergeColumns()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Select Case ws.Name
Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
ws.Range("H1:S1").Select
Case Else
Selection.Merge
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
End With
End Select
Next ws
End Sub
I would appreciate your time regarding the same.
我很感激你的时间。
回答by Siddharth Rout
Is this what you are trying?
这是你正在尝试的吗?
Option Explicit
Sub MergeColumns()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Select Case ws.Name
Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
With ws.Range("H1:S1")
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
End With
End Select
Next ws
End Sub
or if you want to ignore Sheet1 to Sheet4 then try this
或者如果你想忽略 Sheet1 到 Sheet4 然后试试这个
Option Explicit
Sub MergeColumns()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Select Case ws.Name
Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
Case Else
With ws.Range("H1:S1")
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
End With
End Select
Next ws
End Sub
回答by tumchaaditya
If you want to run the same operation for ALL sheets(which is right as per my understanding), then, why do you need switch case?
如果您想对所有工作表运行相同的操作(根据我的理解这是正确的),那么,为什么需要 switch case?
you can just write:
你可以写:
Option Explicit
Sub MergeColumns()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws.Range("H1:S1")
.Merge
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
End With
Next ws
End Sub

