我是Excel VBA编程的新手,我使用的是版本2010.
我正在尝试复制数组中列出的列中的单元格内容,因此我可以将它们粘贴到另一个工作表上。
列将保持不变但我希望该行位于活动单元格的任何位置。代码链接到一个按钮。
当我使用单元格整数对数组进行调暗时,这就像魅力一样。我希望有一种方法可以使数组动态,行号基于活动单元格。
Dim x As Integer
Dim myarray As Variant
x = ActiveCell.Row
myarray = Array("Ax", "Fx", "Ix", "Jx", "Kx", "Rx")
With ThisWorkbook.Worksheets("HANDOVER")
Cells(x, myarrray).Select
Selection.Copy
End With
答案 0 :(得分:2)
您不能将数组作为列参数传递给Cells
。您可以做的是对地址字符串执行简单的Replace
操作,如下所示:
Dim x As Long
Dim myarray As Variant
x = ActiveCell.Row
myarray = "Ax,Fx,Ix,Jx,Kx,Rx"
ThisWorkbook.Worksheets("HANDOVER").Range(Replace(myarray, "x", x)).Copy
答案 1 :(得分:0)
这应该对您有帮助,我有一个自定义函数(见下文)来查看标题并获取相应的列号以便以后重用。
但是,我确实必须修改你的代码(我摆脱了.Select
这是无用的和ressource-greedy)才能使用我的函数,请看下面的组合:
Sub Test_Mabes()
Dim x As Integer, _
myArray As Variant, _
Ws As Worksheet, _
ColNb() As Variant
Set Ws = ThisWorkbook.Worksheets("HANDOVER")
x = Ws.ActiveCell.Row
myArray = Array("Ax", "Fx", "Ix", "Jx", "Kx", "Rx")
ReDim ColNb(UBound(myArray))
For i = LBound(myArray) To UBound(myArray)
ColNb(i) = GetColumnNb(Ws, myArray(i))
Next i
Ws.Cells(x, ColNb).Copy
End Sub
这是功能:
Public Function GetColumnNb(ByVal SheetName As Worksheet, ByVal HeaderName As String) As Integer
Dim ShA As Worksheet
Set ShA = SheetName
For j = 1 To ShA.Cells(1, Columns.Count).End(xlToLeft).Column
If LCase(ShA.Cells(1, j)) <> LCase(HeaderName) Then
Else
GetColumnNb = j
End If
Next j
End Function