我创建了以下代码。宏应该简单地将单元格A2:G3000乘以1,以便格式从文本变为数字。我写的宏是这样做的,但仅适用于活动工作表。我在学习它时使用了For Each / Next循环。
有人可以帮助我在代码中找到我的错误吗?
Sub Format_Change()
Dim sht As Worksheet
For Each sht In Worksheets
Range("M2").Select
ActiveCell.FormulaR1C1 = "=RC[-12]*1"
Range("M2").Select
Selection.AutoFill Destination:=Range("M2:W2"), Type:=xlFillDefault
Range("M2:W2").Select
Selection.AutoFill Destination:=Range("M2:W3000"), Type:=xlFillDefault
Range("M2:W3000").Select
Selection.Copy
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("M2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents
Next sht
End Sub
答案 0 :(得分:5)
尝试下面的代码,正如@Vityata指出的那样,实际上不需要使用这么多m
和Select
,它会大大减慢代码的速度。
尝试下面的代码版本:
Selection
答案 1 :(得分:2)
一般来说代码不好,因为它使用了太多选择等等。请阅读How to avoid using Select in Excel VBA macros。但是,如果你想让它成为一个正在运行的,只需在for-each循环之后添加sht.Select
。
Option Explicit
Sub Format_Change()
Dim sht As Worksheet
For Each sht In Worksheets
sht.Select
Range("M2").Select
ActiveCell.FormulaR1C1 = "=RC[-12]*1"
Range("M2").Select
Selection.AutoFill Destination:=Range("M2:W2"), Type:=xlFillDefault
Range("M2:W2").Select
Selection.AutoFill Destination:=Range("M2:W3000"), Type:=xlFillDefault
Range("M2:W3000").Select
Selection.Copy
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("M2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents
Next sht
End Sub