0

可能重复:
宏将范围复制到具有条件的新工作簿

我没有成功地尝试为以下目的创建宏:将工作簿的范围复制到新工作簿。查看示例 1 中的第一个屏幕截图,我想要实现的是将范围 R4:AB6 复制到一个新工作簿,并附加一个标准。宏应该只复制活动单元格的行包含值的行。示例 1 的第二个屏幕截图显示了宏的结果:一个新工作簿,其中粘贴了基于上述条件的范围。我添加了另一个示例以使我需要更清楚。在示例 2 中,屏幕截图 2 显示了活动单元格为 R7 的起始位置。运行宏的结果将是最终的屏幕截图,其中第 4 行和第 5 行已与活动单元格的行一起复制,并且仅当该行不为空时。

我真的很感激任何帮助,因为我对 vba 还很陌生,并且很长一段时间以来一直在努力解决这个问题!

示例 1 示例 1 示例 2 示例 2

4

1 回答 1

2

这很粗糙,但希望这会有所帮助..

Sub bks()

Application.ScreenUpdating = False
Dim WB1 As Workbook
Dim WB2 As Workbook
Dim name1 As String
Dim name2 As String
Dim colLet As String

'grab name of current workbook
name1 = ThisWorkbook.Name
Set WB1 = Workbooks(name1)


'create new workbook and set it
Workbooks.Add.Activate
name2 = ActiveWorkbook.Name
Set WB2 = Workbooks(name2)

WB1.Activate

Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim m As Integer
Dim mAdjust As Integer
Dim x As Double



'set x equal to number of rows you have
x = 100

Dim colSave() As Double
ReDim colSave(x)

j = 1
k = 1

'the `17` adjust the loop for the R column (17 columns over from 1)
    For i = 1 + 17 To 11 + 17
        For m = 1 To x

'for each row of records, set the first report column to 1 via the array colSave(m)
        If i = 1 + 17 Then
            colSave(m) = 1
        End If
           mAdjust = m + 5
               WB2.Activate
        j = colSave(m)

'convert the column number to column letter
            If i > 26 Then
               colLet = Chr(Int((i - 1) / 26) + 64) & Chr(Int((i - 1) Mod 26) + 65)
            Else
               colLet = Chr(i + 64)
            End If

            WB1.Activate

        'the conditional statements you wanted
                If Cells(mAdjust, i) <> "" Then
                    Range(colLet & "4," & colLet & "5," & colLet & mAdjust).Activate
                        Selection.Copy
                        WB2.Activate
                        Sheets("Sheet1").Cells((m - 1) * 5 + 1, j).Activate
                        ActiveSheet.Paste
                    colSave(m) = colSave(m) + 1
                End If
            Next m
    Next i

Application.ScreenUpdating = True
WB2.Activate

'`j` and `k` allow you to move the paste columns sperately based on your condition.
End Sub
于 2012-12-26T17:11:11.893 回答