我需要将数据从工作簿复制到另一个工作簿,但是当我尝试运行我的宏时,在包含“select”操作的行上获取运行时错误“438”。 感谢所有人,对不起,如果我做了noob错误,但我对vba相对较新:)
这是我的代码:
Private Sub FileChoose_Click()
Dim fd As FileDialog
Dim FileName As String
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
Dim wb2 As Workbook
Set fd = Application.FileDialog(msoFileDialogOpen)
Dim filechosen As Integer
filechosen = fd.Show
fd.Title = "Scegliere il file da confrontare"
fd.InitialView = msoFileDialogViewSmallIcons
fd.Filters.Clear
fd.Filters.Add "Excel File", "*.xlsx"
fd.Filters.Add "Excel File con Macro", "*.xlsm"
fd.FilterIndex = 1
fd.ButtonName = "Apri"
If filechosen <> -1 Then
MsgBox "Nessun File Selezionato"
Else
FileName = fd.SelectedItems(1)
Set wb2 = Workbooks.Open(FileName)
Call Insert(wb2, wb1)
End If
End Sub
Private Sub Insert(wb2 As Workbook, wb1 As Workbook)
Dim myrange As Range
Set myrange = Range("B2:GT22")
For i = 1 To 24
wb2.Worksheets(i).Activate
wb2.ActiveSheet.myrange.Select <--- there is the error
Selection.Copy
wb1.Worksheets(i + 1).Activate
wb1.ActiveSheet.myrange.Select
Selection.Paste
Next i
End Sub
答案 0 :(得分:1)
myrange
变量是范围引用,但您正在使用它作为字符串变量。您实际上可以取消选择方法并使用它:
Private Sub Insert(wb2 As Workbook, wb1 As Workbook)
Dim myrange As String
myrange = "B2:GT22"
For i = 1 To 24
wb2.Worksheets(i).Range(myrange).Copy
wb1.Worksheets(i + 1).Range(myrange).Paste
Next i
End Sub
答案 1 :(得分:1)
不应该使用.Select
的另一个好理由这是你在尝试的吗?
Private Sub Insert(wb2 As Workbook, wb1 As Workbook)
Dim FromRng As Range, ToRng As Range
Dim i As Long
For i = 1 To 24
Set FromRng = wb2.Worksheets(i).Range("B2:GT22")
Set ToRng = wb1.Worksheets(i + 1).Range("B2:GT22")
myrange.Copy ToRng
Next i
End Sub
答案 2 :(得分:0)
看看你在错误发生之前定义MyRange的地方,首先你定义它然后稍后你激活另一张表并尝试访问MyRange,因为它在前一张表中,产生错误,设置MyRange之后:
wb2.Worksheets(i).Activate
它会起作用