I'm making a macro to collect data from multiple Excel files and combine them into one where I can then Plot them all on the same Graph.
Having issues using variables to show which columns to paste to.
cq = ColumnLetter(n)
cp = ColumnLetter(n + 1)
Columns("cq:cp").Select
Where n is changing by 3 each time it loops. It has been pasting all the data in the columns CQ and CP.
I know this is a basic problem and the Code is messy as hell, I don't typically use Excel VBA.
Function ColumnLetter(ByVal intColumnNumber)
Dim sResult
intColumnNumber = intColumnNumber - 1
If (intColumnNumber >= 0 And intColumnNumber < 26) Then
sResult = Chr(65 + intColumnNumber)
ElseIf (intColumnNumber >= 26) Then
sResult = ColumnLetter(CLng(intColumnNumber \ 26)) _
& ColumnLetter(CLng(intColumnNumber Mod 26 + 1))
Else
Err.Raise 8, "Column()", "Invalid Column #" & CStr(intColumnNumber + 1)
End If
ColumnLetter = sResult
End Function
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
cq = ColumnLetter(n)
cp = ColumnLetter(n + 1)
Columns("A:B").Select
Selection.Copy
Windows("Results.xlsx").Activate
Columns("cq:cp").Select
ActiveSheet.Paste
'Change First Worksheet
wb.Worksheets(1).Range("A1") = ColumnLetter(n)
wb.Worksheets(1).Range("B1") = Left(myFile, 9)
'Save and Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
n = n + 3
Loop
Columns("cq:cp).Selectyou're missing a quote. Besides you would only have to paste to range("CP1") , not the entire columns. This is a Function() not a Sub() selects probably wouldn't work very well.