VBA代码在使用F8时工作,但在完全运行时不工作

以下是我的被调用的代码。 它被称为代码,要求用户打开所需的工作簿。 被调用的代码正常工作,当我通过使用F8一步,但它没有创build一个合适的相关表,当我完全运行代码。

Dim nCols As Integer Dim myRange, myCorrel, c As Range Range("A1").CurrentRegion.Select nCols = Selection.Columns.Count Range("B1").Resize(1, nCols - 1).Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select Set myRange = Selection ' create correlation table Application.Run "ATPVBAEN.XLAM!Mcorrel", myRange, _ "Statistics", "C", True Selection.Copy Range("B1").End(xlToRight).Offset(0, 2).Select Selection.PasteSpecial End Sub 

我的关联表代码无法捕获数据标题。 我会收到一堆没有原始列标题计算的相关性。

除非这样,

 Application.Run "ATPVBAEN.XLAM!Mcorrel", myRange, _ "Statistics", "C", True 

…改变了select,那么你可以避免依靠什么是当前的select。 几个嵌套With … End With语句可以重新解释代码,就像您依赖Application.Selection属性的方式一样,但是直接引用所有内容。

 Sub vert() Dim nCols As Long 'this is how to declare multiple range objects Dim myRange As Range, myCorrel As Range, c As Range With Worksheets("Sheet1") '<~~set this worksheet reference! With .Range("A1").CurrentRegion nCols = .Columns.Count With .Resize(.Rows.Count, nCols-1).Offset(0, 1) '<~~all of col B over to the right side Set myRange = .Cells ' create correlation table Application.Run "ATPVBAEN.XLAM!Mcorrel", myRange, _ "Statistics", "C", True 'change formulas to their values .Cells = .Value End With End With End With End Sub 

看起来像将B列全部移到数据的右端,并使用ATPVBAEN.XLAM!Mcorrel进行一些处理。 这留下公式,然后恢复到公式结果(即Range.Value属性 )。

所以你可以看到如何使用With … End With非常像逐步改变select。 主要的区别在于它不会因为外部干扰而改变。


请参阅如何避免使用Excel中的selectVBAmacros来获取更多的方法来摆脱依靠select和activate来实现您的目标。