|
Option Explicit
Dim fileContent As String
Dim currentPosition As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address = "$A$1" Then
Dim filePath As String
filePath = "D:\your_file.txt" '替换为实际文件路径
Open filePath For Input As #1
fileContent = ""
Do While Not EOF(1)
Line Input #1, buf
fileContent = fileContent & buf & vbNewLine
Loop
Close #1
Target.Value = fileContent
currentPosition = 1
End If
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Column = 1 Then 'A 列双击
If currentPosition > 1 Then
currentPosition = currentPosition - 1
Dim startIndex As Long
Dim endIndex As Long
startIndex = InStr(currentPosition, fileContent, vbLf) + 1
endIndex = InStr(startIndex, fileContent, vbLf) - 1
If endIndex = -1 Then
MsgBox "已阅读到上一段末尾"
Target.Value = fileContent
Else
Target.Value = Mid(fileContent, startIndex, endIndex - startIndex + 1)
End If
Else
MsgBox "已在开头"
End If
ElseIf Target.Column = 2 Then 'B 列双击
If currentPosition < Len(fileContent) Then
Dim startIndex As Long
Dim endIndex As Long
startIndex = InStr(currentPosition, fileContent, vbLf) + 1
endIndex = InStr(startIndex, fileContent, vbLf) - 1
If endIndex = -1 Then
MsgBox "已阅读到下一段末尾"
Target.Value = fileContent
Else
currentPosition = endIndex + 1
Target.Value = Mid(fileContent, startIndex, endIndex - startIndex + 1)
End If
Else
MsgBox "已阅读完成"
Target.Value = fileContent
End If
ElseIf Target.Column = 3 Then 'C 列双击
Target.Value = ""
End If
End Sub
这段代码是尝试在Excl中A1单元格内,打开D盘内txt文件的内容,打开后内容显示字节根据该单元格的行距自动调整,双击A列显示打开的TXT文件显示上一段字节,双击B列显示打开的TXT文件显示的下一段字符,双击C列还原A1单元格原有内容,TXT文件阅读到末尾后,提示已阅读完成,并还原A1单元格,但是运行一直错误,提示Private Sub Worksheet_SelectionChange(ByVal Target As Range)这段代码变量未定义,我应该怎么解决。
|
|
|