【问题标题】:Excecute loop within a 'If...Then' statement VBA在'If...Then'语句VBA中执行循环
【发布时间】:2016-06-06 19:09:18
【问题描述】:

我通过在公式中指定单元格并将它们添加到新工作簿中的指定单元格/列中,将多个工作簿中的单元格添加到单个工作簿中。我还想在我的“if..then..With”语句中包含一个 for 循环。我希望我的“for”循环将指定范围 A2:C57 从每个工作表 3、4、5、6、7、8、9 添加到单元格 G、H、I 等中。如何在我当前的 VBA 代码中添加这个循环?

Sub GetData()
Dim MyPath As String
Dim FileName As String
Dim SheetName As String
Dim n As Long
Dim NewRow As Long

MyPath = "C:\attach"
SheetName = "Title"


FileName = Dir(MyPath & "\*.xlsx")
Do While FileName <> ""
 If FileName <> ThisWorkbook.Name Then
   With ThisWorkbook.Sheets("Sheet1")
   NewRow = .Cells(Rows.Count, 1).End(xlUp).Row + 1

  'Transferring cells from worksheet(2)"Title" into "Sheet1" in thisworkbook"
  With .Range("A" & NewRow)
    .Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B4"
    .Value = .Value
  End With
  With .Range("B" & NewRow)
    .Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B5"
    .Value = .Value
  End With
  With .Range("C" & NewRow)
    .Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B6"
    .Value = .Value
  End With
  With .Range("D" & NewRow)
    .Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!B7"
    .Value = .Value
  End With
  With .Range("E" & NewRow)
    .Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!A1"
    .Value = .Value
  End With
  With .Range("F" & NewRow)
    .Formula = "='" & MyPath & "\[" & FileName & "]" & SheetName & "'!A2"
    .Value = .Value
  End With
  'Selects the range A2:C57 from sheets 3,4,5,6,7,8,9
  With .Range("G" & NewRow)
   Dim i As Integer, j As Integer, k As Integer
    k = 1   'row counter for destination sheet
    'loop sheets 3-9
     For i = 3 To 9
         'loop rows 2-57
          For j = 2 To 57
            'if C is not empty
                If WrkBookSrs.Sheets(i).Cells(j, 3).Value <> "" Then
                 'code here to add A:C on this row into this workbook in sheet1 column G.

                         k = k + 1'increment counter for next row
    End If
Next

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    你的解释和伪代码不是很清楚。 您是否要在循环中添加单元格 (A:C) 中所有值的总和? 您的 cmets 仅提到正在使用的列 A:C

    所以如果我理解正确,您应该能够将变量设置为值的总和

    With WrkBookSrs.Sheets(i)
       newGvalue= .Cells(j, 1).Value + .Cells(j, 2).Value + .Cells(j, 3).Value
    End With
    

    【讨论】:

    • 不是添加,只是传输数据。在 A:C 列中
    【解决方案2】:

    像这样添加一个 for 循环。

    For q = 3 To 9
        With ThisWorkbook.Sheets("Sheet" & q)
    

    如果您只想一遍又一遍地包含相同的工作表,这应该可以。当然调整 q 的范围以满足您的规格

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 2019-05-06
      • 2011-08-20
      • 1970-01-01
      • 2013-12-29
      相关资源
      最近更新 更多