Excel:从VBAmacros中省略行/列

借助一些帮助,我已经将两个函数结合在一起,首先将所有数据从“文本”格式转换为“数字”格式。 之后它会将每列设置为固定数量的字符。

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

当运行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.第一个代码

此刻,您正在使用z工作在表单上的所有单元格。 您可以将其减less到UsedRange – 忽略前三行

  • 在使用之前强制UsedRange更新(以避免冗余单元格)
  • testingz超过3行
  • 如果是这样,使用“ Offset和“ Resize三行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.第二个代码

对每个标题单元格执行一个简单的testing,如果它不等于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