下面是我正在研究的一个宏,它使用名为“BW TB”的主表中的数据更新所有“数字”表(即具有数字名称的表)中的一组值。
由于某种原因,子程序“ClearContents”清除了所有数字表中的数据,但也清除了主表中的数据(因此没有使用其他两个子程序复制粘贴),我无法弄清楚为什么!完整的代码如下;请看一下:
Option Explicit
Dim BW As String, FirstRow As Integer, LastRow As Integer, ColNo As Integer, i As Integer
Sub Refresh_Data()
Application.CutCopyMode = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'Defines the range of rows and columns in the refreshed BW query
BW = "BW TB"
Worksheets(BW).Activate
Range("A1").Activate
Dim MyCell As Range
Set MyCell = Cells.Find(What:="Overall Result", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
True, SearchFormat:=False)
FirstRow = MyCell.End(xlUp).Row + 1
LastRow = MyCell.Row - 1
ColNo = MyCell.Column
'loop to update numeric sheets
For i = 1 To Sheets.Count
If IsNumeric(Sheets(i).Name) Then
Call Clearcontents
Call PasteGLCodes
Call PasteTBValues
End If
Next
Call CheckTotals
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Private Sub Clearcontents()
'clears the contents of the sheet of Row 6 to 1000 for every column containing data in Row 6
Dim ColRange As Integer
With Worksheets(i)
ColRange = .Cells(6, .Columns.Count).End(xlToLeft).Column
.Range("A6", .Cells(1000, ColRange)).Clearcontents
End With
End Sub
Private Sub PasteGLCodes()
'Pastes the range of GL codes from ColumnA
With Worksheets(BW)
Range(.Cells(FirstRow, ColNo), .Cells(LastRow, ColNo)).Copy
End With
Worksheets(i).Range("A5").PasteSpecial xlPasteValues
End Sub
Private Sub PasteTBValues()
'Copies the formula from top row and drags to the last row
Range("B5:L5").Copy
Range("B5:L5", Range("B5:L5").Offset(LastRow - FirstRow, 0)).PasteSpecial xlPasteFormulas
'Recalculates the formulae
ActiveSheet.Calculate
'Pastes the values from the second row down to the last row
Range("B6:L6", Range("B6:L6").Offset(LastRow - FirstRow, 0)).Copy
Range("B6").PasteSpecial xlPasteValues
End Sub
Private Sub CheckTotals()
Application.Goto Worksheets("Control sheet").Range("AU114"), True
MsgBox "Update complete - check control totals"
End Sub
如果我将ClearContents替换为:
Private Sub Clearcontents()
Sheets(i).Activate
Range("A6").EntireRow.Select
Range(Selection, Selection.Offset(1000, 0)).Clearcontents
End Sub
它工作正常,但它显然是一个不太干净的解决方案。
与往常一样,任何帮助都非常感谢!
答案 0 :(得分:4)
尝试更改
.Range("A6", .Cells(1000, ColRange)).Clearcontents
到
.Range(.Range("A6"), .Cells(1000, ColRange)).Clearcontents
在您的Clearcontents子目录中。
编辑我发现您的问题:Clearcontents
和PasteGLCodes
都没有激活第i张表格,因此您对PasteTBValues
的通话始终会在您在跑步开始时激活的表格(“BW TB”)。您需要更改最后一个子组,以便它在第i页上运行...
答案 1 :(得分:2)
如果您在工作簿中有任何图表,那么您将引用不同的工作表,如您正在使用的Refresh_Data
方法Sheets
以及您正在使用的ClearContents
方法{{1 }}
Sheets colleciton包含工作表和图表。
Worksheets集合仅包含工作表。
因此,请在WorkSheets
方法中使用Sheets
。