[英]Code not running smooth when switching between workbooks (Excel VBA)
我有一個從表單運行的代碼(如下)。 它對給定范圍內的值求和,並將所有值的總和粘貼到用戶選擇的范圍內。 如果代碼在一個工作簿中執行,則它運行良好。 但是,如果我想要另一個工作簿中的結果並在兩個工作簿之間切換,它運行起來並不順利......
任何建議如何更新此代碼以正常工作?
Private Sub cmdSUM_Click()
Dim arr() As Variant, i As Long, sum As Double
Dim rg As Range
Dim cl As Range
Dim nmr As Double
Dim col As New Collection
Dim output As Range, ws As Worksheet, wb As Workbook
Application.ScreenUpdating = False
Set rg = Selection.SpecialCells(xlCellTypeVisible)
For Each cl In rg
If IsNumeric(cl.Value) Then
If Not cl.Value = 0 Then
nmr = cl.Value
col.Add nmr
End If
End If
Next
ReDim arr(1 To col.Count)
For i = 1 To col.Count
arr(i) = col.Item(i)
Next i
With Application
.ScreenUpdating = True
Set output = .InputBox("Select Range", "Range for pasting SUM", Type:=8)
sum = .WorksheetFunction.sum(arr)
output = sum
.ScreenUpdating = False
End With
With output
Set ws = .Worksheet
Set wb = Workbooks(.Parent.Parent.Name)
End With
wb.Activate
ws.Select
output.Select
Application.ScreenUpdating = True
Unload Me
End Sub
嘗試使用以下代替
Private Sub cmdSUM_Click()
Dim rg As Range, output As Range
Application.ScreenUpdating = False
Set rg = Selection.SpecialCells(xlCellTypeVisible)
On Error Resume Next
Set output = Application.InputBox("Select Range", "Range for pasting SUM", Type:=8)
On Error GoTo 0
If Not output Is Nothing Then
With output
.Value2 = Application.WorksheetFunction.sum(rg)
.Parent.Activate
.Select
End With
End If
Application.ScreenUpdating = True
Unload Me
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.