[ 初めての方へ | 一覧(最新更新順) | 全文検索 | 過去ログ ]
『列の切り取り、貼り付けをVBAで行いたい』(こくぼ)
例えば、X列をA列に、Y列をB列に「切り取り、貼り付け」する操作を、VBAのコードで書くときは、どのようなコードになりますでしょうか?
< 使用 Excel:Office365、使用 OS:Windows10 >
Sub 部課で並び替え()
'
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range( _
"AC2:AC1446"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range( _
"AE2:AE1446"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:AN1446")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub
(こくぼ) 2020/02/06(木) 10:08
可変行に対応するには、何行目までデータがあるかを変数に代入してしまうと良いです。
A列には空欄が無い場合の整形例なぞ。(SortFields.Add2 となっていましたが、Excel2013には無いので、普通のAddに変えています)
Sub test()
Dim iMax As Long
With ActiveWorkbook.Worksheets("Sheet1")
iMax = .Cells(.Rows.Count, "A").End(xlUp).Row
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=.Range("AC2:AC" & iMax), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=.Range("AE2:AE" & iMax), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
.Sort.SetRange .Range("A1:AN" & iMax)
With .Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
End Sub
(???) 2020/02/06(木) 10:54
難しく考えなくても列全体で考えてもいいのでは?
(まっつわん) 2020/02/06(木) 10:55
Sub 部課で並び替え()
Dim rngTable As Range '表のセル範囲
Dim mySort As Sort 'シート上の並べ替えの設定
With ThisWorkbook.Worksheets("Sheet1")
Set rngTable = .Range("A1").CurrentRegion
Set mySort = .Sort
End With
With mySort.SortFields
.Clear
.Add Key:=rngTable.Range("AC1"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.Add Key:=rngTable.Range("AD1"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.Add Key:=rngTable.Range("AE1"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortTextAsNumbers
End With
With mySort
.SetRange rngTable
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
With rngTable
.Columns("X:Y").Cut
.Columns("A").Insert Shift:=xlShiftToRight
End With
Application.CutCopyMode = False
End Sub
(まっつわん) 2020/02/06(木) 11:30
うまくできました。
(こくぼ) 2020/02/06(木) 11:59
[ 一覧(最新更新順) ]
YukiWiki 1.6.7 Copyright (C) 2000,2001 by Hiroshi Yuki.
Modified by kazu.