Excel 选择一列而不使用。选择

Excel 选择一列而不使用。选择,excel,vba,Excel,Vba,我已经在excel中创建了VBA宏。它起作用了;然而,我读到的每个论坛都声明我应该避免使用Select。由于我是一个新手,我不知道如何实现它,也不知道它将如何工作 该代码执行以下操作: 将B列中的内容复制到E列,然后删除B列 列E随后变为列D 格式化列D中的所有单元格以换行文本 在D列上使用“数据文本到列”功能 基于换行符的分隔符。(其他:CTRL J) 只需替换。选择您将使用的方法(操作)或属性(属性)。然后删除Select通常会执行的所有不必要的操作。例如: Sub TestRun(

我已经在excel中创建了VBA宏。它起作用了;然而,我读到的每个论坛都声明我应该避免使用Select。由于我是一个新手,我不知道如何实现它,也不知道它将如何工作

该代码执行以下操作:

  • 将B列中的内容复制到E列,然后删除B列
    • 列E随后变为列D
  • 格式化列D中的所有单元格以换行文本
  • 在D列上使用“数据文本到列”功能
    • 基于换行符的分隔符。(其他:CTRL J)

  • 只需替换。选择您将使用的方法(操作)或属性(属性)。然后删除Select通常会执行的所有不必要的操作。例如:

    Sub TestRun()
        Columns("B:B").Copy Destination:=Columns("E:E")
        Columns("B:B").Delete Shift:=xlToLeft
    
        With Columns("D:D")
            .HorizontalAlignment = xlGeneral
            .VerticalAlignment = xlBottom
            .WrapText = True
            .Orientation = 0
            .AddIndent = False
            .IndentLevel = 0
            .ShrinkToFit = False
            .ReadingOrder = xlContext
            .MergeCells = False
            .ColumnWidth = 25.13
            .TextToColumns Destination:=Range("D1"), DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
            Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
            :="" & Chr(10) & "", FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, _
            1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12 _
            , 1), Array(13, 1), Array(14, 1), Array(15, 1), Array(16, 1), Array(17, 1), Array(18, 1)), _
            TrailingMinusNumbers:=True
    
        End With
    
    End Sub
    

    下面是一个简单的示例,使用
    With
    语句,不使用out-using变量将col2移动到col4

    'Identify your workbook and sheet, change the sheet name as needed
    With ThisWorkbook.Sheets("Sheet1")
    
        'First - Cut col2 
        .Columns(2).EntireColumn.Cut
    
        'Second - Insert col2 at col5 shifting the current col5 to the right. 
        .Columns(5).EntireColumn.Insert Shift:=xlRight
    
        'col3 etc. will then shift left because col2 was cut and moved to col5
    End With
    

    您可以在上述
    With
    语句中使用
    With Columns(4)
    来设置列的格式,尝试编写代码,如果您还有任何问题,请提问。

    而不是
    Columns(“D:D”)。选择
    -
    Dim myRange As Range
    ,然后使用
    Set myRange=Columns(“D:D”)
    -然后使用该对象变量,而不是
    选择
    它可以工作,非常感谢!令人惊叹的!非常感谢你!
    'Identify your workbook and sheet, change the sheet name as needed
    With ThisWorkbook.Sheets("Sheet1")
    
        'First - Cut col2 
        .Columns(2).EntireColumn.Cut
    
        'Second - Insert col2 at col5 shifting the current col5 to the right. 
        .Columns(5).EntireColumn.Insert Shift:=xlRight
    
        'col3 etc. will then shift left because col2 was cut and moved to col5
    End With