我正在为MS Word 2013编写一个大宏,其中一个部分应该是sub,阻止用户编写文本;用户应该能够使用热键(例如ctrl + q)来停止(或启动)这个子(我已经知道如何将热键分配给子)。我对VBA很新。我已经google了答案但是只有指令如何为Excel编写这样的宏,但它在Word中不起作用。有没有办法做到这一点?怎么样? 先感谢您。
Dim startTime As Single
Dim stopTime As Single
Dim timeToRun
Dim totalTime
Dim tmpTime
Dim avg As Long
Public isStart As Boolean
Public Sub hotkeyPressed() 'I wrote module to handle this'
If isStart = True Then
stopButton_Click
Else
startButton_Click
End If
End Sub
Private Sub startButton_Click()
totalTime = tmpTime
startTime = Timer
isStart = True
startButton.Enabled = False
stopButton.Enabled = True
ActiveDocument.Protect _
Type:=wdNoProtection
End Sub
Private Sub stopButton_Click()
isStart = False
stopTime = Timer
tmpTime = totalTime + tmpTime
startButton.Enabled = True
stopButton.Enabled = False
ActiveDocument.Protect _
Type:=wdAllowOnlyReading
End Sub
Private Sub Document_New()
startButton.Caption = "Start!"
stopButton.Caption = "Stop"
isStart = False
Call scheduler
ActiveDocument.Protect _
Type:=wdAllowOnlyReading
On Error GoTo Handler:
Open "KM\" + ActiveDocument.Name + ".txt" For Input As #1
Input #1, line
tmpTime = line
Close #1
Exit Sub
Handler:
tmpTime = 0
End Sub
Private Sub Document_Close()
MyFile1 = "KM\" + ActiveDocument.Name + ".txt"
fnum = FreeFile()
Open MyFile1 For Output As fnum
Print #fnum, totalTime
Close fnum
End Sub
Private Sub scheduler()
timeToRun = Now + TimeValue("00:00:01")
Application.OnTime timeToRun, "getNumberOfLetters"
End Sub
Sub getNumberOfLetters()
If isStart = True Then
numOfLetters = ActiveDocument.Characters.Count
totalTime = Timer - startTime
timeLabel.Caption = totalTime + tmpTime
charLabel.Caption = numOfLetters
setResult
End If
Call scheduler
End Sub
Private Sub setResult()
avg = 60 * numOfLetters / czasLabel.Caption
avg.Caption = avg
End Sub
答案 0 :(得分:2)
您是否尝试过使用.Protect
方法?
Sub ProtectDocument()
ActiveDocument.Protect _
Type:=wdAllowOnlyReading
End Sub
这会阻止用户输入。如有必要,您可以使用VBA取消保护文档:
Sub UnprotectDocument()
ActiveDocument.Protect _
Type:=wdNoProtection
End Sub