試試這個..只需將test1替換爲列名等。
請記住添加列號而不是targetCol,因爲您想對其進行硬編碼。我使用範圍對象來複制數據。
Option Explicit
Sub CopyCode()
'Declaring the variable lColumn as long to store the last Column number
Dim lColumn As Long
'Declaring the variable iCntr as long to use in the For loop
Dim iCntr As Long
Dim lastRow As Long
Dim lastCol As Long, targetCol As Long
Dim wks As Worksheet, targetWks As Worksheet
Dim rng As Range
Dim fCol As String
' Set wks so it is the activesheet
Set wks = ThisWorkbook.Sheets("Sheet1")
Set targetWks = ThisWorkbook.Sheets("Sheet2")
lastCol = wks.Cells(1, wks.Columns.Count).End(xlToLeft).Column
'Assigning the last Column value to the variable lColumn
lColumn = lastCol
'Using for loop
For iCntr = lColumn To 1 Step -1
If LCase(wks.Cells(1, iCntr)) Like LCase("Test1") Then
' Find column letter
fCol = GetColumnLetter(iCntr)
lastRow = wks.Range(fCol & wks.Rows.Count).End(xlUp).Row
' Declare range object
Set rng = wks.Range(fCol & "2:" & fCol & lastRow)
' Use Range object to copy data
rng.Copy _
Destination:=targetWks.Cells(1, targetCol) ' Replace targetCol with number of column (A=1, B=2, etc.)
End If
If LCase(wks.Cells(1, iCntr)) Like LCase("Test2") Then
' Find column letter
fCol = GetColumnLetter(iCntr)
lastRow = wks.Range(fCol & wks.Rows.Count).End(xlUp).Row
' Declare range object
Set rng = wks.Range(fCol & "2:" & fCol & lastRow)
' Use Range object to copy data
rng.Copy _
Destination:=targetWks.Cells(1, targetCol) ' Replace targetCol with number of column (A=1, B=2, etc.)
End If
If LCase(wks.Cells(1, iCntr)) Like LCase("Test") Then
' Find column letter
fCol = GetColumnLetter(iCntr)
lastRow = wks.Range(fCol & wks.Rows.Count).End(xlUp).Row
' Declare range object
Set rng = wks.Range(fCol & "2:" & fCol & lastRow)
' Use Range object to copy data
rng.Copy _
Destination:=targetWks.Cells(1, targetCol) ' Replace targetCol with number of column (A=1, B=2, etc.)
End If
' etc etc
Next
End Sub
Function GetColumnLetter(colNum As Long) As String
Dim vArr
vArr = Split(Cells(1, colNum).Address(True, False), "$")
GetColumnLetter = vArr(0)
End Function
你想要一個宏按鈕或如何運行宏嗎? – Niclas
@Niclas宏按鈕將是偉大的。我需要的只是宏能夠複製將被硬編碼的列。 –
@Niclas我在第2段和第3段的末尾添加了更多細節,使其更加清晰。 –