這段代碼有效,但我覺得可能有更好的方法來撰寫它,因為我是 VBA 新手,對它了解不多。任何建議表示贊賞!
基本上,從單元格 AL2 開始,我將遍歷每一列,直到找到第 2 行中的第一個空單元格。然后,我在該空單元格的左側插入一個新列。找到空單元格幾乎是即時的,但插入新列需要大約 15-20 秒。這是我的代碼:
Range("AL2").Select
Do Until IsEmpty(ActiveCell)
ActiveCell.Offset(0, 1).Select
Loop
ActiveCell.EntireColumn.Insert
uj5u.com熱心網友回復:
不要使用.Selectand 而不是回圈和測驗每個單元格,您可以使用StartCell.End(xlToRight)它直接跳轉到最后使用的單元格。
Option Explicit
Public Sub InsertColumn_Example()
Dim ws As Worksheet
Set ws = ActiveSheet ' better define your worksheet like `Set ws =ThisWorkbook.Worksheets("Sheet1")
' find next empty cell in the row of StartCell
Dim NextEmptyCell As Range
Set NextEmptyCell = GetNextEmptyCellByColumn(StartCell:=ws.Range("AL2"))
' insert column
NextEmptyCell.EntireColumn.Insert
End Sub
Public Function GetNextEmptyCellByColumn(ByVal StartCell As Range) As Range
If IsEmpty(StartCell) Then
' if StartCell cell is empty return it
Set GetNextEmptyCellByColumn = StartCell
ElseIf IsEmpty(StartCell.Offset(ColumnOffset:=1)) Then
' if cell right of StartCell is empty return it
Set GetNextEmptyCellByColumn = StartCell.Offset(ColumnOffset:=1)
Else
' otherwise jump to the next empty cell right of StartCell
Set GetNextEmptyCellByColumn = StartCell.End(xlToRight).Offset(ColumnOffset:=1)
End If
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/491499.html
