简体   繁体   English

使用VBA打开Excel文件并复制表格

[英]Opening an excel file & copying sheets using VBA

I need to copy a couple of excel sheets ("Y", "X") from one file to the same sheet in another excel file (call it Z - the same file that I'm using the VBA on). 我需要将几个Excel工作表(“ Y”,“ X”)从一个文件复制到另一个Excel文件(称为Z-与我使用VBA的文件相同)中的同一工作表。 my limitation is that the name and path of the first excel file (with the X,Y) are changing, therefore I'm trying to write something more generic using the "as String" and the Application.GetOpenFilename() command but I'm receiving an error. 我的局限性是第一个excel文件(带有X,Y)的名称和路径正在更改,因此我试图使用“ as String”和Application.GetOpenFilename()命令编写更通用的名称,但是我m收到错误。

Tried to separate into 2 different subs 尝试分成2个不同的子

Sub BrowseForFile()
    Dim sFileName As String
    sFileName = Application.GetOpenFilename(, , "open the file: " )

    If sFileName = "false" Then Exit Sub
    MsgBox sFileName
    Workbooks.Open (sFileName)
    Workbooks(sFileName).Sheets("X").Activate
    Stop
  1. Runtime Error 9 运行时错误9
  2. file doesn't find (1004 I think) 找不到文件(我认为是1004)

If the user presses the Cancel button then the GetOpenFilename function returns a boolean False not a string "false" so you need to test for If sFileName = False Then and declare it as Variant . 如果用户按下“ 取消”按钮,则GetOpenFilename函数将返回布尔False而不是字符串"false"因此您需要测试If sFileName = False Then其声明为Variant

If you open a workbook always reference it to a variable so you can use that to access the workbook easily 如果打开工作簿,请始终将其引用到变量,以便您可以轻松地使用该变量访问工作簿

Dim OpenedWb As Workbook
Set OpenedWb = Workbooks.Open(sFileName)

Then you can use the variable Wb to reference the workbook you opened 然后,您可以使用变量Wb来引用您打开的工作簿

OpenedWb.Worksheets("X").Activate

Note that using .Select and .Activate is a bad practice and should be avoided ( How to avoid using Select in Excel VBA ). 请注意,使用.Select.Activate是一种不好的做法,应避免使用如何避免在Excel VBA中使用Select )。 Instead use another reference to reference your workbook. 而是使用另一个引用来引用您的工作簿。

Dim ws As Worksheet
Set ws = OpenedWb.Worksheets("X")

And access a range like ws.Range("A1").Value for example. 并访问诸如ws.Range("A1").Value类的范围。


Sub BrowseForFile()
    Dim sFileName As Variant 'needs to be variant because cancel returns a boolean False
    sFileName = Application.GetOpenFilename(, , "open the file: " )

    If sFileName = False Then Exit Sub

    MsgBox sFileName

    Dim OpenedWb As Workbook
    Set OpenedWb = Workbooks.Open(sFileName)

    Dim ws As Worksheet
    Set ws = OpenedWb.Worksheets("X")

    MsgBox ws.Range("A1").Value 'output the value of `A1` in worksheet `X` of workbook `sFileName`
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM