创建包含WorkSheet数据的公共变量

时间:2016-09-02 20:54:14

标签: arrays excel vba excel-vba variant

简化的Excel代码:

Public MyFile As String
Public varSheetA As Variant
Public SelRangeA As Range
Public wsCopy As Excel.Worksheet

Sub SelectFile_Click()

MyFile = Application.GetOpenFilename()  'Aquire filepath from user
If (MyFile <> "False") Then
Range("B1").Value = "File Found"
End If
End Sub

Sub LoadFile_Click()

Dim WbOne As Workbook
Dim strRangeToCheck As String
strRangeToCheck = "A1:T2000"

Set WbOne = Workbooks.Open(MyFile) 'Open that file
Set wsCopy = WbOne.Worksheets(1)   'Try to copy
Set varSheetA = wsCopy.Range(strRangeToCheck) 'Try to copy
Set SelRangeA = wsCopy.Range(strRangeToCheck) 'Try to copy

WbOne.Close 'This is where we lose the references & values
End Sub

Sub DisplayFile_Click()

Range("A4").Value = varSheetA(1, 1)
End Sub

此程序的最终结果是在Range或Variant Array中包含WorkSheet(1)中的值,以便我可以根据需要编辑和显示它们,并最终将值复制回原始文件。但是,当我运行此代码时,LoadFile_Click退出时,我初始化的所有公共变量都为空(更具体地说,当WbOne关闭时。

以前我的代码看起来像varSheetA = WbOne.Worksheet(1).Range(strRangeToCheck),虽然我目前正在测试不同的方法,因为这种方式似乎不起作用。

任何人都会看到我正在尝试做的任何根本问题?谢谢!

1 个答案:

答案 0 :(得分:2)

Option Explicit

Public MyFile As String
Public varSheetA As Variant


Sub SelectFile_Click()
    MyFile = Application.GetOpenFilename()  'Aquire filepath from user
    If (MyFile <> "False") Then
        Range("B1").Value = "File Found"
    End If
End Sub

Sub LoadFile_Click()

    Const strRangeToCheck As String = "A1:T2000"

    With Workbooks.Open(MyFile)
        varSheetA = .Worksheets(1).Range(strRangeToCheck).Value
        .Close False
    End With

End Sub

Sub DisplayFile_Click()
    Range("A4").Value = varSheetA(1, 1)
End Sub