我有一些代码
Sub Test2()
Dim ws As Worksheet
Dim rCell As Range
Dim i As Long
Dim resultArray() As String
Dim resultIndex As Long
'ClearImmediateWindow
'Application.VBE.Windows("Immediate").Visible = True
'Debug.Print vbLf & Format(Now(), "dd-mmm-yyyy HH:mm:ss")
Application.VBE.Windows("Immediate").Close
Application.VBE.Windows("Immediate").Visible = True
Set ws = ThisWorkbook.ActiveSheet ' Adjust this to get the sheet you need
resultIndex = 0 ' Initialize the result index
For i = 1 To 12
Set rCell = Cells(i, "C")
If HasAnyBorder(rCell) Then
' Store the result in the array
ReDim Preserve resultArray(resultIndex)
resultArray(resultIndex) = "Cell C" & i & " True"
Else
ReDim Preserve resultArray(resultIndex)
resultArray(resultIndex) = "Cell C" & i & " False"
End If
resultIndex = resultIndex + 1
Next i
' Print the accumulated results to the Immediate Window
For i = LBound(resultArray) To UBound(resultArray)
Debug.Print resultArray(i)
Next i
End Sub
Sub ClearImmediateWindow()
' Simulate pressing Ctrl+G (to activate the Immediate Window)
Application.SendKeys "^g"
' Simulate pressing Ctrl+A (to select all content)
Application.SendKeys "^a"
' Simulate pressing the Delete key (to clear the selected content)
Application.SendKeys "{DEL}"
Application.SendKeys "{f7}" ' Go back to VBE Project Window
End Sub
Function HasAnyBorder(rngCell As Range) As Boolean
HasAnyBorder = rngCell.Value <> "" Or _
rngCell.Borders(xlEdgeTop).LineStyle <> xlNone Or _
rngCell.Borders(xlEdgeBottom).LineStyle <> xlNone Or _
rngCell.Borders(xlEdgeLeft).LineStyle <> xlNone Or _
rngCell.Borders(xlEdgeRight).LineStyle <> xlNone
End Function
问题是,每次我运行此命令时,立即窗口都会被清除,然后填充其他 debug.print 项目,速度太快,以至于无法阅读。对每条消息采取定时方法可以减慢速度,但在最后一条消息之后它仍然会清除窗口。
我希望
Debug.Print ""
作为其他人建议的第一行代码
Application.VBE.Windows("Immediate").Close
或
Application.VBE.Windows("Immediate").Visible = True
要测试代码,请在“C”列中各个单元格的左、右、上、下边框,结果应该类似于:
Cell C1 True
Cell C2 True
Cell C3 True
Cell C4 False
Cell C5 False
Cell C6 False
Cell C7 False
Cell C8 False
Cell C9 False
Cell C10 False
Cell C11 False
Cell C12 False
为您的考虑干杯:Stephen G6SGA
另一种解决方案是记录到文件而不是立即窗口。以下内容将执行此操作(如果您使用的是 Windows 设备……我知道这是一个假设,如果您没有使用,我们深表歉意):
Sub LogToFile(text As String)
Dim i As Integer
i = FreeFile()
Open Environ$("localappdata") & "\my_log.txt" For Append Access Write As #i
Print #i, text
Close #i
End Sub
该文件将被称为“my_log.txt”,并将位于您的“C:\Users%username%\AppData\Local”文件夹中(其中 %username% 是您的实际用户名)。
像这样使用它(因此将
Debug.Print
替换为 LogToFile
):
LogToFile "Hello"
LogToFile "World"
如果您想自动为文件中的每一行添加日期/时间戳,请将
Print #i, text
更改为 Print #i, Now & ": " & text
。
...然后您不需要对立即窗口执行任何操作!