Excel:从VBA宏中省略行/列

时间:2012-03-29 03:41:24

标签: excel vba excel-vba

在一些帮助下,我将两个将协同工作的功能放在一起,首先将我的所有数据从“文本”格式转换为“数字”格式。之后,它会将每列设置为固定数量的字符。

我正在使用的两个子例程如下所示,但我无法弄清楚如何省略各个函数的某些行/列。

运行psAdd函数时,我想省略该范围中的前3行,而对于FormatFixedNumber函数,我想省略几列。后者的问题是我有1000多列数据和一个包含1或0的键标题行,表示是否应该转换列。

如何修改此代码以跳过第一个子组中的前3行,以及在第二个子组中标记为0的多个列?

Sub psAdd()  
    Dim x As Range 'Just a blank cell for variable
    Dim z As Range 'Selection to work with

    Set z = Cells
    Set x = Range("A65536").End(xlUp).Offset(1)
    If x <> "" Then
        Exit Sub
    Else
        x.Copy
        z.PasteSpecial Paste:=xlPasteAll, Operation:=xlAdd
        Application.CutCopyMode = False 'Kill copy mode
    End If
    x.ClearContents 'Back to normal
End Sub

Sub FormatFixedNumber()

    Dim i As Long

    Application.ScreenUpdating = False
    For i = 1 To lastCol 'replace 10 by the index of the last column of your spreadsheet
        With Columns(i)
            .NumberFormat = String(.Cells(2, 1), "0") 'number length is in second row
        End With
    Next i
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:3)

<强> 1。第一个代码

目前,您正在使用z处理工作表上的所有单元格。您可以将其减少到UsedRange - 忽略前三行

  • 强制UsedRange在使用之前更新(以避免冗余的单元格)
  • 测试z是否超过3行
  • 如果是,请使用zOffset

    Resize调整为三行
    Sub psAdd()
    Dim x As Range    'Just a blank cell for variable
    Dim z As Range    'Selection to work with
    ActiveSheet.UsedRange
    Set z = ActiveSheet.UsedRange
    If z.Rows.Count > 3 Then
        Set z = z.Cells(1).Offset(3, 0).Resize(z.Rows.Count - 3, z.Columns.Count)
    End If
    'using Rows is better than hard-coding 65536 (bottom of xl03 - but not xl07-10)
    Set x = Cells(Rows.Count,"A").End(xlUp).Offset(1)
    If x <> "" Then
        Exit Sub
    Else
        x.Copy
        z.PasteSpecial Paste:=xlPasteAll, Operation:=xlAdd
        Application.CutCopyMode = False    'Kill copy mode
    End If
    x.ClearContents    'Back to normal
    End Sub
    

<强> 2。第二个代码

对每个标题单元格运行一个简单的测试,如果它不等于0则继续。假设标题单元格在第1行,那么

Sub FormatFixedNumber()
    Dim i As Long
    Application.ScreenUpdating = False
    For i = 1 To lastCol    'replace 10 by the index of the last column of your spreadsheet
        If Cells(1, i) <> 0 Then
            With Columns(i)
                .NumberFormat = String(.Cells(2, 1), "0")    'number length is in second row
            End With
        End If
    Next i
    Application.ScreenUpdating = True
End Sub