I am working on a code that will automate a process. I want it to copy from various files to other files with formulas, calculate, and then back again.
I have encountered, a message 'Run-time error '1004', the pastespecial method of range class failed' , when tried to paste. The message appears ONLY when I am using variables to declare the first cell, in order to copy a range of values. When I use a direct cell description everything works fine. I'm also using a custom function for obtaining the column letter, of a given field name.
Function ActiveColumnName(fieldname As String, fieldnames_line As Integer) As String
Range("A" & fieldnames_line & ":AB" & fieldnames_line).NumberFormat = "@"
Cells.find(What:=fieldname, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
ActiveColumnNumber = ActiveCell.Column
Dim m As Integer
Dim ActiveColumnName As String
ActiveColumnName = ""
Do While (ActiveColumnNumber > 0)
m = (ActiveColumnNumber - 1) Mod 26
ActiveColumnName = Chr(65 + m) + ActiveColumnName
ActiveColumnNumber = Int((ActiveColumnNumber - m) / 26)
Loop
End Function
sub main ()
Dim firstrow_data_main As Integer
Dim firstrow_fieldnames_main As Integer
firstrow_data_main = 16
firstrow_fieldnames_main = 15
Range(ActiveColumnName("<FIELDNAME>", firstrow_fieldnames_main) & firstrow_data_main, Range(ActiveColumnName("ÄÅÔÅ", firstrow_fieldnames_main) & Rows.Count).End(xlUp).Offset(-1)).Select
Application.CutCopyMode = False
Selection.Copy
Workbooks.Open help_file '"help_file" is any given .xls path with formulas
Dim firstrow_data_help As Integer
Dim firstrow_fieldnames_help As Integer
firstrow_data_help = 7
firstrow_fieldnames_help = 4
'NOW WHEN I USE THIS, DOESN'T WORK:
-> Range(ActiveColumnName("<FIELDNAME>", firstrow_fieldnames_help) & firstrow_data_help).Select
'WHEN I USE THIS, WORKS FINE:
-> Range("L7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End Sub
When it doesn't work, it opens the .xls
, and the desirable cell is indeed selected, but no pate. I understand that has something to do with the clipboard, but I cannot figure it out. Any suggestions?