2017-04-21 68 views
1

我正在使用VBA宏插入列,從而它在A列中搜索文本字符。 我的代碼正確運行。但是,該文件看起來像是要崩潰了。我將建立在宏觀上並希望它順利運行。 有沒有辦法來優化我的代碼VBA代碼性能問題

代碼:

Sheets("Annual Rec").Select 
Columns("B:B").Select 
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 
Selection.NumberFormat = "General" 
Range("B2:B" & Range("A" & Rows.Count).End(xlUp).Row).Formula = "=ISTEXT(RC[-1])" 
Range("B2:B" & Range("A" & Rows.Count).End(xlUp).Row).Select 
Selection.Copy 
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
    :=False, Transpose:=False 
Application.CutCopyMode = False 
+5

嘗試[避免選擇/激活](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) – Rdster

+0

您可以通過以下方式啓動刪除你的3個''Select''和4個''Selection'' –

+0

並將你的'Copy' /'Paste'改爲'Range(「B2:B」&Range(「A」&Rows.Count).End(xlUp)。 Row).Value = Range(「B2:B」&Range(「A」&Rows.Count).End(xlUp).Row).Value' – Jordan

回答

2

下面的代碼與您的相同,只是沒有不必要的SelectSelection

Option Explicit 

Sub CopyColPasteVal() 

Application.ScreenUpdating = False 

With Sheets("Annual Rec") 
    .Columns("B:B").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 
    .Columns("B:B").NumberFormat = "General" 
    With .Range("B2:B" & .Range("A" & .Rows.Count).End(xlUp).Row) 
     .Formula = "=ISTEXT(RC[-1])" 
     .Copy 
     .PasteSpecial xlPasteValues 
    End With 
    Application.CutCopyMode = False 
End With 

Application.ScreenUpdating = True 

End Sub 
+0

現在添加一些東西來說'.Copy''.PasteSpecial xlPasteValues '相當於'.Value = .Value';) – YowE3K

+0

@YowE3K打算小睡一下,如果你喜歡它,我會讓你升級我的答案;) –

+0

我要睡了一夜,不算短小睡打破了我! :) – YowE3K

0

試試這個:

Application.ScreenUpdating = False 
'your code 
Application.ScreenUpdating = True 

,避免選擇陳述,他們是相當緩慢的。