VBA Excel 初始化表单 - 找不到变量

问题描述 投票:0回答:1

我正在尝试通过 Excel 表单中的超链接打开文本文件。 因此,在 B 列中有一个超链接将用户引导至文本文件。 由于文本文件位于 SharePoint 环境中,我希望它在用户窗体而不是浏览器中打开。 该文件需要可编辑。

Worksheet_FollowHyperlink() 正确找到了文件路径,但不知何故,它没有传递到要在 UserForm_Initialize() 中使用的公共变量中。 因此,当需要打开表单时,我收到错误“找不到路径”。

我似乎无法理解它。

Excel 工作表背后的代码

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    Dim fileName As String
    Dim filePath As String
    Dim frm As UserForm1 ' Declare a variable to hold the UserForm instance

    ' Extract the file name from the hyperlink's address
    fileName = Mid(Target.Address, InStrRev(Target.Address, "/") + 1)

    ' If the file has an extension, remove it
    If InStr(fileName, ".") > 0 Then
        fileName = Left(fileName, InStrRev(fileName, ".") - 1)
    End If

    ' Construct the file path assuming the Content folder is in the same directory as the workbook
    filePath = ThisWorkbook.Path & "\" & fileName & ".txt"
    Debug.Print "File Path in Worksheet_Initialize 1: " & filePath ' Debugging line

    ' Create a new instance of the UserForm
    Set frm = New UserForm1
    Debug.Print "File Path in Worksheet_Initialize 2: " & filePath ' Debugging line
    ' Set the file path and show the UserForm
    frm.filePath = filePath
    Debug.Print "File Path in Worksheet_Initialize 3 : " & filePath ' Debugging line
    
    frm.Show
End Sub

UserForm1 后面的代码

Public filePath As String ' Store the file path
Private Sub UserForm_Initialize()
    Dim fileContent As String
    Dim fileNum As Integer
    Debug.Print "File Path in UserForm_Initialize: " & filePath ' Debugging line

    If filePath <> "" Then
        On Error GoTo ErrorHandler
        fileNum = FreeFile
        Open filePath For Input As #fileNum
        fileContent = Input$(LOF(fileNum), #fileNum)
        Close #fileNum

        ' Display the file content in the TextBox
        Me.TextBox1.Text = fileContent
    Else
        MsgBox "File path not found."
        Unload Me
    End If
    Exit Sub

ErrorHandler:
    MsgBox "Error loading file: " & Err.Description
    Unload Me
End Sub

Private Sub btnSave_Click()
    ' Save the content from the TextBox back to the file
    Dim fileNum As Integer
    Dim fileContent As String

    fileContent = Me.TextBox1.Text ' Ensure you have a TextBox named TextBox1

    On Error GoTo ErrorHandler
    fileNum = FreeFile
    Open filePath For Output As fileNum
    Print #fileNum, fileContent
    Close fileNum

    MsgBox "File saved successfully!"
    Unload Me
    filePathSet = False ' Reset the flag after use
    Exit Sub

ErrorHandler:
    MsgBox "Error saving file: " & Err.Description
End Sub

Private Sub btnCancel_Click()
    ' Close the form without saving
    Unload Me
End Sub
excel vba forms
1个回答
0
投票

实例化表单后,您的 userform_Initialize 事件就会立即运行。这意味着您在此事件运行之前需要设置的任何变量或属性尚未设置。我通常不使用该事件,我创建自己的初始化子,然后在设置所有属性后可以调用它。

© www.soinside.com 2019 - 2024. All rights reserved.