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

时间:2017-08-29 21:07:45

标签: excel vba excel-vba excel-2007

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

以下代码无法复制列E; Union函数似乎存在问题,因为我将#N/A分配到隐藏工作表的该列中,而不是该列的值。有什么问题?

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 -  https://stackoverflow.com/questions/11746478/excel-macro-run-time-error-1004
  Hidden_sheet.Unprotect MyPassword

 'References:
 ' dynamic referencing: https://stackoverflow.com/questions/45889866/how-to-assign-values-from-one-sheet-into-hidden-sheet-using-excel-vba-and-skip/45889960#45889960
 ' adding text:         https://stackoverflow.com/questions/20612415/adding-text-to-a-cell-in-excel-using-vba
 ' Union to exclude column: https://stackoverflow.com/questions/2376995/exclude-some-columns-while-copying-one-row-to-other
 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行)

1 个答案:

答案 0 :(得分:0)

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

根据Dirk Reichel

  

Union()是一个范围(范围可以是非连续的)[,而 .Value [是]直接值或值数组。 [A] rrays不能是非连续的[。]

一种解决方案是分别分配不连续的范围(E)。