【问题标题】:Excel: Omitting rows/columns from VBA macroExcel:从 VBA 宏中省略行/列
【发布时间】:2012-04-12 17:03:31
【问题描述】:

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

下面列出了我正在使用的两个子例程,但我不知道如何为各个函数省略某些行/列。

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

如何修改此代码以跳过第一个 sub 中的前 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

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    1.第一个代码

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

    • 强制UsedRange 在使用前更新(以避免冗余单元格)
    • 测试z 是否超过 3 行
    • 如果是这样,使用 OffsetResizez 的大小调整为三行

      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
    

    【讨论】:

    • 如果我正确理解了关于第二段 od 代码的问题,0 位于第 2 行,因此条件为 If Cells(2, i) &lt;&gt; 0 Then
    • 我还希望第二段代码像第一段代码一样省略前几行标题。
    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 2014-12-30
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    相关资源
    最近更新 更多