以下是整个代码,以备您查看:https://pastebin.com/TbewRRCc。我的问题是,在检查之后,我的Collection确实只是由我想要的列组成。所以,如果我想要有三列,那么columnsToCopy.Count将= 3,当我只复制columnToCopy(3)时.Copy结果将只是一列。但是当我通过循环来建立这三列的联合时,这些列之间的所有列也将在联合中。
例如。假设我正在复制第1列,第13列和第30列。粘贴表将是从1到30的所有列。这不是我想要的。我只想要列1,13和30 ......所以这个特殊的Colelction共有三列。
关于可能导致我的问题的任何想法,以及如何解决它?
For arrayLoop = LBound(iq_Array) To UBound(iq_Array)
' Take copy of potential ref and adjust to standard if required
checkStr = iq_Array(arrayLoop)
If hasIQs And Left(checkStr, 3) <> "iq_" Then checkStr = "iq_" & checkStr
' Look for existence of corresponding column in local copy array
pCol = 0
For iCol = 2 To colNumb
If checkStr = IQRef(iCol) Then
pCol = iCol
Exit For
End If
Next iCol
If pCol > 0 Then
' Paste the corresponding column into the forming table
columnsToCopy.Add ShRef.Columns(pCol).EntireColumn
End If
Next arrayLoop
If columnsToCopy.Count > 1 Then 'data was added
' Copy table
Dim unionVariable As Range
Set unionVariable = columnsToCopy(1)
For k = 1 To columnsToCopy.Count
Set unionVariable = xlApp.Union(unionVariable, columnsToCopy(k))
Next k
unionVariable.Copy
Next k
unionVariable.Copy
答案 0 :(得分:1)
根据您的解释(仅包含您想要的列的集合),这对我有用
Option Explicit
Public Sub TestUnion()
Dim ws1 As Worksheet, ws2 As Worksheet, k As Long
Dim unionVariable As Range, columnsToCopy As Collection
Set ws1 = Sheet1
Set ws2 = Sheet2
Set columnsToCopy = New Collection
columnsToCopy.Add ws1.UsedRange.Columns(1)
columnsToCopy.Add ws1.UsedRange.Columns(3)
columnsToCopy.Add ws1.UsedRange.Columns(5)
Set unionVariable = columnsToCopy(1)
For k = 2 To columnsToCopy.Count
Set unionVariable = Union(unionVariable, columnsToCopy(k))
Next k
unionVariable.Copy ws2.Cells(1) 'copy AND paste
End Sub
我刚刚将For循环更改为从2开始,并在与副本相同的行上执行粘贴