下面是我叫的代码。它被调用为一个代码,要求用户打开所需的工作簿。当我通过 F8 使用它时,被调用的代码正常工作,但是当我完全运行代码时,它无法创建正确的关联表。
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
我的关联表代码无法捕获数据头。我会收到一堆没有原始列标题计算的相关性。
答案 0 :(得分:1)
除非这个,
Application.Run "ATPVBAEN.XLAM!Mcorrel", myRange, _
"Statistics", "C", True
...更改选择,然后您可以避免完全依赖当前选择。一些嵌套的With ... End With statements可以重新解释您的代码,就像您依赖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 property)。
所以你可以看到使用With ... End With非常像逐步改变选择。主要区别在于它不会因为任何外部干扰而发生变化。
有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros。