Forum Discussion
gms4b
Aug 05, 2019Brass Contributor
modify VBA code to include dynamic columns instead of static
I have the following code which looks for the word "unknown" in column "4" (of sheet "Raw Data") and then copies the corresponding row of data to a different sheet ("undiluted"). However, sometimes t...
Haytham Amairah
Aug 07, 2019Silver Contributor
Hi,
Please try this code to move the needed columns from Undiluted to UndilutedPLUS.
Sub test2()
Application.ScreenUpdating = False
Dim i As Integer
i = 0
Sheets("Undiluted").Activate
Dim columnNamesArray() As Variant
columnNamesArray = Array("Analyte Peak Name", "Sample Type", "Rack Type", "Vial Position")
Dim columnName As Variant
For Each columnName In columnNamesArray
Sheets("Undiluted").Activate
Dim columnNumber As Integer
columnNumber = Cells.Find(What:=columnName, After:=Range("A1"), LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Column
Cells(1, columnNumber).EntireColumn.Copy
Sheets("UndilutedPLUS").Activate
Range("A1").Activate
ActiveCell.Offset(0, i).Select
ActiveSheet.Paste
i = i + 1
Next columnName
Range("A1").Activate
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
Please note that you have to define the needed columns you want to move in the code.
You can insert them into the columnNamesArray.
Hope that helps
gms4b
Aug 07, 2019Brass Contributor
Thanks for the code. I like the idea of creating an array so I don't have to define each column individually.
Right now there is a Runtime Error 1004 (Activate method of Range Class failed) at the line that says:
Range("A1").activate
I added this code as a second command button. The first button does the first part of code (and works fine). The second button activates this new code.
Greg