原因你的錯誤,在於以下部分:
Dim y As Workbook
Set y = Sheets("Sheet1").Select
您定義y
爲工作簿,但試圖將Worksheet
對象分配給它,您添加Select
出於某種原因,這是挑釁不推薦。
它應該是(如果工作簿是打開的):
Set y = Workbooks("YourBookName")
你的代碼的其餘部分會工作得很好。
然而,讀您的文章,我覺得你的意思來定義y As Worksheet
。
然後你的代碼的其餘部分應該是:
Set y = Sheets("Sheet1")
val = x.Sheets("Sheet2").Range("A1").Value
y.Range("A1").Value = val
編輯1:更新後的代碼(根據PO的新數據)
Option Explicit
Sub test()
Dim x As Workbook
Dim y As Workbook
Dim Val As Variant
Dim filename As String
Set y = ThisWorkbook ' set ThisWorkbook object (where this code lies)
Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")
Val = x.Sheets("Sheet2").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = Val
x.Close
End Sub
編輯2:代碼複製列A:E直到最後一行有數據
Option Explicit
Sub test()
Dim x As Workbook
Dim y As Workbook
Dim Val As Variant
Dim filename As String
Dim LastCell As Range
Dim LastRow As Long
Set y = ThisWorkbook ' set ThisWorkbook object (where this code lies)
Set x = Workbooks.Open("D:\Mikz\xxx.xlsx")
With x.Sheets("Sheet2")
' use the find method to get the last row in column A:E
Set LastCell = .Columns("A:E").Find(What:="*", After:=.Cells(1), Lookat:=xlPart, LookIn:=xlFormulas, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
If Not LastCell Is Nothing Then ' find was successful
LastRow = LastCell.Row ' get last Row with data
End If
Val = .Range("A1:E" & LastRow).Value ' save range in 2-D array
End With
' resize the range from A1 through column E and the last row with data in copied workbook
y.Sheets("Sheet1").Range("A1").Resize(LastRow, 5).Value = Val
x.Close
End Sub
我添加了代碼,這是你最後提到的。我得到一個類型不匹配的錯誤 – Mikz
@Mikz你是否也將Dim y更改爲Worksheet? –
錯誤發生時,當試圖打開x中提到的工作簿,而ist加載,然後我得到錯誤,類型不匹配 – Mikz