简体   繁体   English

我在Excel和VBA中得到一个数组“类型不匹配”

[英]I get an array “Type mismatch” in Excel and VBA

I get "Type mismatch" when trying to copy a simple one column into an array and back into another column. 尝试将简单的一列复制到数组中并复制回另一列时,出现“类型不匹配”。 Here's my code (just the relevant bit): 这是我的代码(只是相关的位):

Sub CopyRangesViaArrays()

 'Declaring variables
 Dim srcWkb As Workbook
 Dim destWkb As Workbook

 Dim srcYears() As Double
 Dim destYears As Range

 Dim L As Long

 Set srcWkb = Workbooks("Arrivals.xlsx")
 Set destWkb = Workbooks("OvernightStays.xlsm")

 L = srcWkb.Worksheets.Count
 z = 0

 'Looping through src Workbook sheets
 For C = 1 To L
    ReDim srcYears(26, 0)
    srcYears = srcWkb.Worksheets(C).Range("A3:A28")

    Set destYears = destWkb.Worksheets(10).Range("A2").Offset(z, 0)
    destYears.Value = srcYears
    z = z + 26
 Next C

As you probably see, I'm also having trouble with offsetting the destination range by the number of years taken into an array (there are 43 Sheets so there will be 43 different srcRanges taken up into an array and written to the destRange). 正如您可能看到的那样,我还无法将目标范围偏移到数组中使用的年数(有43个工作表,因此将43个不同的srcRanges合并到数组中并写入destRange)。

Many thanks! 非常感谢!

EDIT: I've also tried this as per instructions 编辑:我也按照说明尝试过

Dim srcYears As Range
Dim destYears As Range

Breaks at this line: 在此行中断:

destYears.Resize(26, 1).Value = srcYears.Value

I tried omitting the last .Value from the problematic line - still nothing. 我试着从有问题的行中省略最后一个.Value-仍然没有。

If you do Dim srcYears() As Variant , then your code will work. 如果将Dim srcYears() As Variant ,则您的代码将起作用。 I am not certain about why you can't declare it as a strongly typed array (eg, As Double ) but I'm guessing that a range's .Value , which can be represented as an array, cannot be handled this way, because the .Value array is not necessarily of that data type, and will not be coerced to that type by an assignment. 我不确定为什么不能将其声明为强类型数组(例如, As Double ),但是我猜测范围的.Value (可以表示为数组)无法用这种方式处理,因为.Value数组不一定是该数据类型,也不会通过赋值强制转换为该类型。 My guess is that a Range.Value is always of type Variant, because a range can contain string, numeric, or error values. 我的猜测是Range.Value 始终为Variant类型,因为范围可以包含字符串,数字或错误值。

You can assign directly from one range to another: 您可以直接从一个范围分配给另一个范围:

 Dim srcYears as Range

 For C = 1 To L
    '## not needed: ReDim srcYears(26, 0)
    Set srcYears = srcWkb.Worksheets(C).Range("A3:A28")

    Set destYears = destWkb.Worksheets(10).Range("A2").Offset(z, 0)
    '## resize the destination range to ensure it _
        accommodates the source Range, then assign directly.
    destYears.Resize(26,1).Value = srcYears.Value
    z = z + 26
 Next C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM