【发布时间】:2019-09-04 02:17:10
【问题描述】:
我想通过 FilePath 将我正在打开的工作簿中的一张工作表复制到另一个包含我正在运行的宏的工作簿中。
我遇到的问题是,每当我复制和粘贴文件时,宏都会创建一个新的工作簿并将数据粘贴到该工作簿的第一张工作表中。我在第二个工作簿中定义了一个特定的工作表来粘贴代码,所以我不确定为什么我的粘贴目标是一个随机工作簿。
Public filepath As String
Sub FileOpenDialogBox()
'Display a Dialog Box that allows to select a single file.
'The path for the file picked will be stored in fullpath variable
With Application.FileDialog(msoFileDialogFilePicker)
'Makes sure the user can select only one file
.AllowMultiSelect = False
'Filter to just the following types of files to narrow down selection options
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Store in fullpath variable
fullPath = .SelectedItems.Item(1)
End With
filepath = fullPath
'It's a good idea to still check if the file type selected is accurate.
'Quit the procedure if the user didn't select the type of file we need.
If InStr(fullPath, ".xls") = 0 Then
Exit Sub
End If
'Open the file selected by the user
'Workbooks.Open fullpath
End Sub
Sub CopySheet()
'Module 1 FilePath import as Variable
MsgBox filepath
Dim spo_book As Workbook
Dim target_book As Workbook
Set spo_book = ActiveWorkbook
Set target_book = Workbooks.Open(filepath)
Dim dst_sheet As Worksheet
Dim target_sheet As Worksheet
Set dst_sheet = spo_book.Sheets("SPO Data")
Set target_sheet = target_book.Sheets("Untimed Parts")
target_sheet.Copy
dst_sheet.Paste
End Sub
预期的结果是复制粘贴将通过我的 FileDialog 从选择的工作簿复制到我设置为变量 dst_sheet 的名为“SPO DATA”的工作表中,我认为这可能是一个范围问题和我试图输入一个范围,但它说数据不匹配,所以我回到我的工作表粘贴。
【问题讨论】:
-
@urdearboy 我有,但我见过很多人用路径定义两个工作簿但这个宏将分发给其他人并且定义路径不是一个可行的解决方案他们所有人都能够编辑宏以使其适用于他们。我尝试只定义我想复制的书,但即使这样也行不通。
-
如何做到这一点也有很好的记录在这里。您的全部问题(分段)都存在于此处。搜索问题的各个组成部分的问题。移动工作表与对话选择器无关 - 单独搜索这些主题并将解决方案组合在一起。如果不这样做,您实际上是在要求其他人为您完成您的工作项目。 stackoverflow.com/questions/26392482/…
-
可能不是最漂亮的,但获取路径,移动工作表,然后另存为...
-
我已将问题编辑为更具描述性,并对其进行了细化以使其更窄。我在某些领域取得了一些进展,所以这个问题应该只是关于我在工作簿之间复制和粘贴的全部问题..