无法为非连续数据列分配范围联合的值

Value of Union of Ranges failing to be assigned for non-contiguous data column

我正在尝试将一个 sheet 的单元格 A13:E300 分配给另一个 sheet,省略 D 列。

以下代码无法复制列 EUnion 函数似乎有问题,因为我将 #N/A 分配给隐藏 sheet 上的该列,而不是该列的值。怎么了?

Private Sub AddTemplate_Click()
 Dim Exposed_sheet As Worksheet, Hidden_sheet As Worksheet, MyPassword As String

 Set Exposed_sheet = Sheets("Exposed Sheet")
 Set Hidden_sheet = Sheets("Hidden")

  MyPassword = "string"
  'Reference: carriage return in msgbox http://www.ozgrid.com/forum/showthread.php?t=41581
  If InputBox("Please enter the password to continue." & vbNewLine & vbNewLine _
   & "Note: The string you type will be exposed, i.e. not '***'." & vbNewLine _
   & "Note: This will save the Excel file!", "Enter Password: Enter the correct string.") <> MyPassword Then
     Exit Sub
  End If

 ' Reference: .Protect -  
  Hidden_sheet.Unprotect MyPassword

 'References:
 ' dynamic referencing: 
 ' adding text:         
 ' Union to exclude column: 
 With Hidden_sheet
    .Cells(1, Columns.Count).End(xlToLeft).Offset(1, 3).Resize(UBound(Exposed_sheet.Range("B6", "D9").Value, 1), UBound(Exposed_sheet.Range("B6", "D9").Value, 2)).Value = Exposed_sheet.Range("B6", "D9").Value
    .Cells(1, Columns.Count).End(xlToLeft).Offset(1, 6).Value = "Volume/Protocol"
    .Cells(1, Columns.Count).End(xlToLeft).Offset(6, 3).Resize( _
     UBound(Union(Exposed_sheet.Range("A13:C300"), Exposed_sheet.Range("E13:E300")).Value, 1), 4).Value = _
                                      Union(Exposed_sheet.Range("A13:C300"), Exposed_sheet.Range("E13:E300")).Value
    ' If you change the order putting this prior, you must change the offsets or the cell they count from. -- DB, Aug 28 2017
    .Cells(1, Columns.Count).End(xlToLeft).Offset(0, 3).Resize(1, 3).Merge
    .Cells(1, Columns.Count).End(xlToLeft).Offset(0, 3).Value = Exposed_sheet.Range("A1").Value
 End With

 Hidden_sheet.Protect MyPassword

 ActiveWorkbook.Save

End Sub

顺便说一句,我也对更灵活的代码感兴趣:它不需要是 300:只需要到最后一行数据——数据集由空白行分隔。总共应该少于 150 行)

范围和数组是不同的对象类型,因此需要不同的方法。具体来说,UBound returns 数组的下标,而 Union returns 一个 Range 对象。 (显然,区域是 Range 对象(的组成部分)的子集。)

根据Dirk Reichel,

Union() is a range (and ranges can be non-contiguous)[, whereas] .Value [is] either a direct value or an array of values. [A]rrays cannot be non-contiguous[.]

一种解决方案是单独分配该非连续范围 (E)。