[英]Working with columns in a range in Excel VBA
I have a function that compares two columns and returns true or false. 我有一个比较两列并返回true或false的函数。 I have another function that takes a range as an input, and should do all pairwise comparisons of the columns in that range.
我还有另一个函数将范围作为输入,并且应该对该范围内的列进行所有成对比较。
However I seem to be drawing a blank at extracting (and storing) columns from a range. 但是,我似乎在从范围中提取(和存储)列时处于空白状态。 The function exits when I ask for the ith column.
当我要求第i列时,该函数退出。 This is my code:
这是我的代码:
Function CompareAllColumns(r As Range, o As Range)
Dim numCols As Integer
Dim i As Integer
Dim j As Integer
Dim col1 As Range
Dim col2 As Range
Dim Matches As Integer
Matches = 0
numCols = r.Columns.Count
Dim ac1 As String
Dim ac2 As String
Dim a As String
a = r.Address
For i = 1 To numCols - 1
col1 = r.Columns(i).Select
ac1 = col1.Address
For j = i + 1 To numCols
col2 = r.Columns(j).Select
If (Compare(col1, col2)) Then
o.Value = "Columns " & i & " and " & j & " are the same"
o = o.Offset(1).Select
Matches = Matches + 1
End If
Next
Next
CompareAllColumns = Matches
End Function
It exits on the line col1 = r.Columns(1).Select
- the Select
is there experimentally but makes no difference to correct execution. 其离开上线
col1 = r.Columns(1).Select
-该Select
是有实验但没有差别来纠正执行。
You have to Set
objects, you can't use the default Let
with them. 您必须
Set
对象,不能将默认的Let
与它们一起使用。
Also, as this appears to be a UDF (based on your comment "It exits on the line col1 = r.Columns(1).Select
", rather than you saying that it crashes out on that line), you need to be aware that your code won't be permitted to make changes to Excel cells other than by returning a value from the function. 另外,由于这似乎是UDF(根据您的注释“它退出到
col1 = r.Columns(1).Select
,而不是您说它在该行崩溃了),所以您需要知道除非通过从函数返回值,否则将不允许您的代码对Excel单元格进行更改。
Function CompareAllColumns(r As Range, o As Range)
Dim numCols As Integer
Dim i As Integer
Dim j As Integer
Dim col1 As Range
Dim col2 As Range
Dim Matches As Integer
Matches = 0
numCols = r.Columns.Count
Dim ac1 As String
Dim ac2 As String
Dim a As String
a = r.Address
For i = 1 To numCols - 1
'use Set for an object
Set col1 = r.Columns(i)
ac1 = col1.Address
For j = i + 1 To numCols
'use Set for an object
Set col2 = r.Columns(j)
If Compare(col1, col2) Then
'You can't set values within a UDF
'o.Value = "Columns " & i & " and " & j & " are the same"
'You can't "Select" things within a UDF
'o = o.Offset(1).Select
Matches = Matches + 1
End If
Next
Next
CompareAllColumns = Matches
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.