【问题标题】:Storing a worksheet name for use in another sub存储工作表名称以在另一个子中使用
【发布时间】:2013-08-26 14:29:48
【问题描述】:

我正在使用一个子过程将文件路径/工作簿和工作表存储在公共变量中,然后模块中的其他子过程可以访问这些变量。下面是一些示例代码:

Public myfp As String
Public mywb As Workbook
Public myws As Worksheet

Sub FilePaths()
    myfp = Application.GetOpenFileName(Title:="Please select the file.")
    Set mywb = Workbooks.Open(myfp, 0)
    If Left(mywb.Sheets(1).Name, 2) = "01" Then
        Set myws = mywb.Sheets(1)
    Else
        Set myws = mywb.Sheets(2)
    End If
    mywb.Saved = True
    mywb.Close
Exit Sub

Sub Stuff()
    Dim wb As WorkBook
    Dim ws As Worksheet
    Set wb = ActiveWorkbook
    Set ws = wb.Sheets(1)
    ws.Range("A1").Value = wb.ws.Range("A1").Value
End Sub

所以我的第一个子确定我需要哪个表,我的第二个子应该将此表单元格的值放入我的表中。但是我得到的只是错误。我想这可能是因为我必须打开文件,所以我尝试了一些我知道应该可行的方法:

SUb Stuff()
    Range("A1").Formula = "='[" & myfp & "]" & myws & "'!A1"
End Sub

但是这也不起作用。我做错了什么?

【问题讨论】:

    标签: variables excel public vba


    【解决方案1】:

    在您的测试示例中,您使用的是wbws 对象,而不是它们的名称。试试这个:

    Public myfp As String
    Public myWbName As String
    Public myWsName As String
    
    Sub FilePaths()
    Dim myWb As Workbook
    
    myfp = Application.GetOpenFilename(Title:="Please select the file.")
    Set myWb = Workbooks.Open(myfp, 0)
    myWbName = myWb.Name
    If Left(myWb.Sheets(1).Name, 2) = "01" Then
        myWsName = myWb.Sheets(1)
    Else
        myWsName = myWb.Sheets(2).Name
    End If
    myWb.Saved = True
    myWb.Close
    End Sub
    
    Sub Stuff()
        Range("A1").Formula = "='[" & myfp & "]" & myWsName & "'!A1"
    End Sub
    

    【讨论】:

    • 这似乎只是部分起作用,使用底部的“东西”子,我在公式栏中得到这个 ='[C:\MacroFiles\Files\[My Long File Name 20 08 2013.xlsx]01Sheet]My Long File Name 2'!A1 所以由于某种原因它似乎搞砸了,我不知道为什么?
    【解决方案2】:

    在第一个 Stuff 中,一旦 ws 被设置,使用: something = ws.Range("A1").Value

    你不需要 wb.ws

    在第二个 Stuff 中,您需要在创建公式时使用字符串变量 myws.Name 而不是 myws

    【讨论】:

      【解决方案3】:

      ws 对象前面删除wb 限定符。

      改变这个:

      ws.Range("A1").Value = wb.ws.Range("A1").Value
      

      到这里:

      ws.Range("A1").Value = ws.Range("A1").Value
      

      【讨论】:

        猜你喜欢
        • 2017-07-12
        • 1970-01-01
        • 2017-06-25
        • 2022-01-19
        • 2020-10-17
        • 2012-08-18
        • 2017-08-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多