gpt4 book ai didi

vba - Excel:从 VBA 宏中省略行/列

转载 作者:行者123 更新时间:2023-12-03 03:01:33 25 4
gpt4 key购买 nike

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

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

运行 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 处理工作表上的所有单元格。您可以将其减少到 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

关于vba - Excel:从 VBA 宏中省略行/列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com