4个不同行中动态范围内的单元格值的动态流行

时间:2014-07-17 22:00:23

标签: excel excel-vba vba

目标:我想用方法Contagenation构建4个不同的字符串。我在工作表(" Calc")中的4行(第32行到第35行)的每一行中都有动态的列数(第4列到maxCol)。 4个不同的字符串应存储在单元格(A1,A2,A3,A4)中的另一个工作表(" CreateColumns")

问题:我编写了以下代码来实现该目标,但在工作表中(" CreateColumns")4行中的每一行都填充了相同的值=工作表中第35行的最后一个值(&# 34; Calc")而不是预期的4个不同值。

问题:我的代码中有什么错误?

Sub CreateColumns()
Dim maxCol As Integer
Dim x As String
Dim rng As Range
Dim cel As Range
Dim i As Long
Dim row As Long
Dim y As Long
    Sheets("Calc").Select
    maxCol = Cells(32, columns.Count).End(xlToLeft).column
      For row = 32 To 35
      Sheets("Calc").Select
      Cells(row, 4).Activate
         For i = 4 To maxCol
            With Worksheets("Calc")
                Set rng = Range(.Cells(row, 4), .Cells(row, maxCol))
            End With            
         x = ""
            For Each cel In rng
                x = x & cel.Value
                  For y = 1 To 4
                    Sheets("ColCreate").Cells(y, 1).Value = x
                  Next
             Next
         Next
      Next
End Sub

1 个答案:

答案 0 :(得分:1)

您的代码中的问题是您粘贴到工作表“ColCreate”的部分有点不合适 - 对于每个最外层循环的出现,它应该出现一次,并且“y”增量

我稍微修改了下面的代码,应该提供预期的结果

Sub CreateColumns()
    Dim maxCol As Integer
    Dim x As String
    Dim rng As Range
    Dim cel As Range
    Dim i As Long
    Dim row As Long
    Dim y As Long
    Sheets("Calc").Select
    maxCol = Cells(32, Columns.count).End(xlToLeft).Column
    y = 1
    For row = 32 To 35
       Sheets("Calc").Select
       Cells(row, 4).Activate
       For i = 4 To maxCol
          With Worksheets("Calc")
              Set rng = Range(.Cells(row, 4), .Cells(row, maxCol))
          End With
          x = ""
          For Each cel In rng
              x = x & cel.Value
          Next
       Next
    Sheets("ColCreate").Cells(y, 1).Value = x
    y = y + 1
    Next
End Sub