列番号に基づいて、選択した列をあるワークシートから別のワークシートにコピーできます。しかし、ある日、ソース ファイルの途中に列を追加することにするかもしれません。列名に基づいて列をコピーすると、これは問題になりません。以下は私が持っているコードです。コメント部分は、列番号に基づいて実際のコピーが行われる場所で、列ラベルに置き換えようとしています。列ラベルはPrice Number
、House Price
、 、Address
およびCost
:
Sub CommercialView()
Dim wrkbk, sourceBk As Workbook
Set sourceBk = Application.ActiveWorkbook
'Clear Filter for all Columns START
With ActiveSheet
If .AutoFilterMode Then
If .FilterMode Then
.ShowAllData
End If
Else
If .FilterMode Then
.ShowAllData
End If
End If
End With
'Clear Filter from all Columns END
'Copy the required columns and add them to the destination spreadsheet START
Workbooks.Add
Set wrkbk = Application.ActiveWorkbook
sourceBk.Activate
wrkbk.Activate
sourceBk.Activate
Range("A1,B1,C1,D1,E1,G1,H1,I1,R1,V1,W1,X1").EntireColumn.Select 'BASED ON COLUMN NO.
Selection.Copy
Range("A2").Select
wrkbk.Activate
ActiveSheet.Paste
Selection.AutoFilter
'Copy the required columns and add them to the destination spreadsheet END
'To remove data validation START
Cells.Select
With Selection.Validation
.Delete
.Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
:=xlBetween
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
'To remove data validation END
wrkbk.Activate
wrkbk.Sheets("Sheet1").Select
ActiveSheet.Range("$A$1:$L$4000").AutoFilter Field:=10, Criteria1:= _
"Completed - Requires Review from Pricing"
'Copy the Status Definitions tab to the new worksheet START
sourceBk.Sheets("2. Status Definitions").Copy _
after:=ActiveWorkbook.Sheets("Sheet1")
'Copy the Status Definitions tab to the new worksheet END
wrkbk.Sheets("Sheet1").Select
Range("A5").Select
ActiveWorkbook.SaveAs ("C:\Users\test\Desktop\DOD\Change Status Request Report\Commercial View\Internal Change Status Request Report - Commercial View - " & Format(Now, "yyyy-mm-dd"))
ActiveWorkbook.Close
End Sub