新的VBA試圖弄清楚。使用代碼嘗試從各種文件自動複製到具有公式的文件,計算並再返回。 當我嘗試粘貼時,遇到了'運行時錯誤'1004',範圍類的pastespecial方法失敗'消息。該消息僅在使用變量聲明第一個單元格時出現,以便複製一系列值。 當即時通訊使用直接單元格描述一切工作正常。 我還使用自定義函數來獲取給定字段名稱的列字母。無法粘貼 - Excel VBA
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, DOESNT 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
當它不工作時,它打開.xls和它的確選擇了理想的細胞,但沒有腦袋。我知道這與剪貼板有關,但無法弄清楚。有什麼建議麼?
1.除去所有的選擇和激活通過直接參照的細胞,見[HERE](http://stackoverflow.com/questions/ 10714251/how-to-avoid-using-select-in-excel-vba-macros)2.查看「Cells()」而不是Range,避免將列號轉換爲字母的整個需求, )'使用數字。 3.當值是唯一需要的時候避免剪貼板,並簡單地將值賦給新單元格(這將要求兩個範圍的大小相同,因此請使用Resize())4.始終表示範圍的父表單它會減少錯誤。 –