填充2个单元格之间的值

时间:2019-08-12 15:08:00

标签: excel vba

我在宏中有一些代码,该代码自动填充每行2个单元格之间的值。它只是复制相同的值。

该代码运行得很好,但是在某些行中只有1个值,并且会直接复制到该行的末尾。

我试图添加一个If语句,但我认为条件不对,因此无法正常工作

function getDataToMaster() { 
  var folder = DriveApp.getFolderById("******************");
  var contents = folder.getFiles();
  var sheetMaster = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  while (contents.hasNext()) {    
    var file = contents.next();
    if (file.getMimeType() !== "application/vnd.google-apps.spreadsheet") { 
     continue;
    } 
    SpreadsheetApp.openById(file.getId()).getSheets()
      .forEach(function (sheet) { 
        var colToCheck = 7;
        sheet.getDataRange().getValues()
          .forEach(function (row, index) { 
            if (row[colToCheck - 1] != "copied") { 
              sheetMaster.appendRow(row);
              sheet.getRange(index + 1, colToCheck).setValue("copied");
              SpreadsheetApp.flush();
            } 
          });
      });
  } 
}

如果该行中只有一个值,则期望它什么也不做。

1 个答案:

答案 0 :(得分:0)

我倾向于将start和end列保存在几个变量中,并有一个单独的循环来填充值:

Sub Fill()

Dim wS As Worksheet
    Dim LastRow As Double
    Dim LastCol As Double
    Dim i As Double
    Dim j As Double
    Dim k As Double
    Dim RowVal As String
    Dim startCol, endCol As Long


    Set wS = ThisWorkbook.Sheets("Overview")
    LastRow = LastRow_1(wS)
    LastCol = LastCol_1(wS)

    For i = 7 To LastRow
    startCol = 0
    endCol = 0
    With wS
        For j = 8 To LastCol

                If .Cells(i, j) <> vbNullString And startCol = 0 Then
                    'First non-empty cell found
                    RowVal = .Cells(i, j).Value
                    startCol = j
                Else
                    'Next non-empty cell found
                    If .Cells(i, j) <> vbNullString And startCol > 0 Then
                        endCol = j
                        Exit For
                    End If
                End If
        Next j

        ' Now fill values
        For j = startCol + 1 To endCol - 1
            .Cells(i, j).Value = RowVal
        Next j

    End With 'wS
    Next i
End Sub

'LastRow_1 and LastCol_1 as before.