【问题标题】:Excel VBA Print Array to WorksheetExcel VBA 将数组打印到工作表
【发布时间】:2018-05-12 18:18:14
【问题描述】:

根据我在这个网站上找到的一个例子,我做了以下过程。它仅将数组的第一个元素打印到整个范围中,而不是将每个元素打印到范围的每个单元格中。你知道我做错了什么吗? 谢谢, 崩溃

i = 2
Do Until Cells(i, 1) = "" 'loops through IDs in 1st column of spreadsheet
    If Cells(i, 1) > "" Then 'if it finds an ID
        GoSub CommentsColor 'sub that calculates a color -> thisColor
    End If
    ReDim Preserve colors(i - 2) 'start array at zero
    colors(i - 2) = thisColor 'populate array
    thisColor = "" 'clear variable
    i = i + 1 'go to next ID in 1st column of spreadsheet
Loop

'set range
Set colorData = ActiveWorkbook.Worksheets("Movement_Data").Range(Cells(2, thisCol), Cells(i - 1, thisCol))
colorData.Value = colors 'print array to worksheet

【问题讨论】:

  • cpearson.com/excel/ArraysAndRanges.aspx 你可能需要 Application.Transpose(colors) 。不确定尺寸。见链接。
  • 我无法将您的评论标记为正确,但确实如此。我改变的只是 Application.Transpose(colors) 并且它有效。
  • 没问题 ;-)

标签: arrays vba excel printing


【解决方案1】:
  1. 您的范围和单元格引用不专门属于该工作表;它们属于 activesheet。

    with ActiveWorkbook.Worksheets("Movement_Data")
        Set colorData = .Range(.Cells(2, thisCol), .Cells(i - 1, thisCol))
    end with
    
  2. 转置数组以匹配您的目的地。

    colorData = application.transpose(colors) 'print array to worksheet
    
  3. 最好根据数组简单地调整目标的大小。

    ActiveWorkbook.Worksheets("Movement_Data").Cells(2, thisCol).resize(ubound(colors)+1, 1) = application.transpose(colors)
    

【讨论】:

  • 关于 activeworkbook 的好点...不是必需的。我添加了它以确保我正在查看正确的范围,但这不是必需的,因为我只在活动工作表上运行它。最后,我只需要 Application.Transpose(colors) 。我不认为我必须转置一维数组。
  • 一维数组等于一行多列。要将其输入一列和多行,您需要转置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多