我正在尝试使用我发现here的代码片段。
Sub foo()
Dim x As Workbook
Dim y As Workbook
Dim wbname As String
Dim lastcol As Long
wbname = Replace(ActiveWorkbook.name, ".xlsx", "")
'## Open both workbooks first:
Set x = Workbooks.Open("N:\blah\deposit\" & wbname & "*.xlsx")
lastcol = Cells(1, Columns.Count).End(xlToLeft).Column
mycol = GetColumnLetter(lastcol)
'Now, copy what you want from x:
x.Sheets("sheet1").Range("mycol:mycol").Copy
x.Close
'Now, paste to y worksheet:
y.Sheets("sheet1").Range("mycol:mycol").PasteSpecial
End Sub
Function GetColumnLetter(colNum As Long) As String
Dim vArr
vArr = Split(Cells(1, colNum).Address(True, False), "$")
GetColumnLetter = vArr(0)
End Function
我似乎无法找到如何复制最后一列。它说错误9下标超出范围。
我尝试了x.Sheets("sheet1").Columns(lastcol).Copy
x.Sheets("sheet1").Range("mycol").copy
,x.Sheets("sheet1").Range(mycol)
和x.Sheets("sheet1").Range(Columns(mycol)).Copy
我还应该做些什么或宣布什么? 我勉强不明白为什么这不起作用。 :(
答案 0 :(得分:0)
大大简化您的代码
Sub foo()
Dim x As Workbook
Dim y As Workbook
Dim wbname As String
Dim lastcol As Long
wbname = Replace(ActiveWorkbook.name, ".xlsx", "")
'## Open both workbooks first:
Set x = Workbooks.Open("N:\blah\deposit\" & wbname & "*.xlsx")
lastcol = Cells(1, Columns.Count).End(xlToLeft).Column
'Now, copy what you want from x:
x.Sheets("sheet1").Columns(lastcol).Copy
'Now, paste to y worksheet:
y.Sheets("sheet1").Columns(lastcol).PasteSpecial
x.Close
End Sub
您不需要该功能来实现您的尝试