如何将部分VBA数组粘贴到excel范围

时间:2014-08-07 14:32:43

标签: excel-vba vba excel

以某种方式可以将vba数组的一部分传递到excel范围吗?

我需要做这样的事情:

dim testday() as Variant
testday = Sheets("raw").Range("E745:BN745").Value
Sheets("raw").Range("E745:BN745").Value = ""
Sheets("Interface").Range("B4:E4") = testday(3, 4, 5, 6).Value

但这不起作用......有没有办法解决这个问题? THX!

3 个答案:

答案 0 :(得分:2)

您可以 切片 Array使用Index功能

Sub Slicer()
 Dim testday() As Variant
 testday = Sheets("raw").Range("E745:BN745").Value
 Sheets("raw").Range("E745:BN745").Value = ""
 Sheets("Interface").Range("B4:E4")= Application.Index(testday, 1, Array(3, 4, 5, 6))
End Sub

答案 1 :(得分:1)

如果要复制的数组是一维的,并且需要复制连续的单元格,则可以使用CopyMemory函数:

Option Explicit
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" _
    Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)


Sub test()
  Dim vArr(), vArr2()
  Dim lCnt As Long
  Dim lStartIndex As Long, lFinishIndex As Long, lLength As Long


  With Application
    vArr = .Transpose(.Transpose(Range("A1:R1").Value2))
  End With

  lStartIndex = 3
  lFinishIndex = 6
  lLength = lFinishIndex - lStartIndex + 1

  ReDim vArr2(1 To lLength)

  CopyMemory vArr2(1), vArr(lStartIndex), lLength * 16

  For lCnt = LBound(vArr2) To UBound(vArr2)
    Debug.Print vArr2(lCnt)
  Next lCnt

  Range("A2").Resize(1, UBound(vArr2)).Value2 = vArr2

End Sub

第一行测试

67.2    9   57.2    boo 52  64  76  39  48  50  28  54  96  29  98  25  68  19

返回

57.2    boo 52  64

在第二行。 因此,您的代码段将更改为

dim testday(), testday2()
With Application  ' Value2 is faster than Value
  testday = .Transpose(.Transpose(Sheets("raw").Range("E745:BN745").Value2))
End With
Sheets("raw").Range("E745:BN745").ClearContents   ' Good suggestion by JFC
CopyMemory testday2(1), testday(3), 4 * 16        ' Variant = 16 Bytes
Sheets("Interface").Range("B4:E4").Value2 = testday2  ' I would do Resize instead

我希望这有帮助!

答案 2 :(得分:0)

你可以:

  • 使用循环将所需的值复制到新阵列,并将其写入您的范围。如果您经常这样做,您可以编写一个可重用的函数来执行此操作。或者,

  • "raw"表中只读您需要的内容,并将其写入您的范围,如下图所示。这可能是您特定情况下最简单的解决方案。


Dim testday() As Variant
testday = Sheets("raw").Range("G745:J745").Value ' only read what you need
Sheets("raw").Range("E745:BN745").ClearContents
Sheets("Interface").Range("B4:E4") = testday(3, 4, 5, 6).Value