Sub NapiMaker()
Dim wb As Workbook
Set wb = ActiveWorkbook
Debug.Print wb.Name
Dim MyFile As String
If MyFile = "" Then
MyFile = Application.GetOpenFilename()
Workbooks.Open (MyFile)
wb.Activate
Dim WS_Count As Integer
Dim I As Integer
WS_Count = wb.Worksheets.Count
For I = 1 To WS_Count
wb.Worksheets(I).Range("B7").Copy Workbooks(MyFile).Worksheets(1).Range("A16")
wb.Worksheets(I).Range("B8").Copy Workbooks(MyFile).Worksheets(1).Range("B16")
wb.Worksheets(I).Range("B10").Copy Workbooks(MyFile).Worksheets(1).Range("D16")
wb.Worksheets(I).Range("B11").Copy Workbooks(MyFile).Worksheets(1).Range("J16")
wb.Worksheets(I).Range("B5").Copy Workbooks(MyFile).Worksheets(1).Range("F16")
wb.Worksheets(I).Range("B14").Copy Workbooks(MyFile).Worksheets(1).Range("E16")
Workbooks(MyFile).Worksheets("1").Range("A16").EntireRow.Insert
Next I
End If
End Sub
我想要以下内容: - 我打开一个文件。 - 按CRTL + K. - 让我选择一个文件。 - 将指定的单元格复制到所选文件。
我找不到问题。
它位于For
循环
答案 0 :(得分:2)
作为Workbooks
集合的索引传递的文件名似乎不允许包含路径。 (我确信我曾在某个地方看到它。)因此Workbooks("abcdef.xlsx")
会起作用,但Workbooks("C:\Temp\abcdef.xlsx")
不会。
以下代码将Workbook
对象分配给打开的工作簿,然后使用该对象在后续语句中引用它,因此无需在Workbooks
集合中使用索引。
Sub NapiMaker()
Dim wb As Workbook
Dim wb1 As Workbook
Set wb = ActiveWorkbook
Debug.Print wb.Name
Dim MyFile As String
If MyFile = "" Then ' myFile will always be blank at this point
MyFile = Application.GetOpenFilename()
Set wb1 = Workbooks.Open(MyFile)
Dim WS_Count As Integer
Dim I As Integer
WS_Count = wb.Worksheets.Count
For I = 1 To WS_Count
wb.Worksheets(I).Range("B7").Copy wb1.Worksheets(1).Range("A16")
wb.Worksheets(I).Range("B8").Copy wb1.Worksheets(1).Range("B16")
wb.Worksheets(I).Range("B10").Copy wb1.Worksheets(1).Range("D16")
wb.Worksheets(I).Range("B11").Copy wb1.Worksheets(1).Range("J16")
wb.Worksheets(I).Range("B5").Copy wb1.Worksheets(1).Range("F16")
wb.Worksheets(I).Range("B14").Copy wb1.Worksheets(1).Range("E16")
'Changed "1" to 1
wb1.Worksheets(1).Range("A16").EntireRow.Insert
Next I
End If
End Sub