VBA:Sub写入日志文件

编程入门 行业动态 更新时间:2024-10-07 15:23:37
本文介绍了VBA:Sub写入日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一组在我的工作簿中定义的宏,我想向用户提供在日志文件中记录与这些宏相关的事件的选项。

I have a set of macros defined in my workbook, and I'd like to offer the user the option to log events related to those macros in a log file.

我通过在ThisWorkbook中创建以下内容来启动日志:

I initiate the log by creating the following in ThisWorkbook:

Public writeLog as Boolean Public logWrite as Object Public log as Object Private Sub Worksheet_Open() Dim prompt as Integer prompt = MsgBox("Would you like to log events for this session?", vbYesNo, "Log Events?") If prompt Then writeLog = True Set logWrite = CreateObject("Scripting.FileSystemObject") Set log = logWrite.CreateTextFile("C:/TEST.txt", False) Else writeLog = False End If End Sub

然后,我创建了一个程序,我可以使用这个过程来写入这个对象的参数,我已经存储在自己的模块中:

I then created a procedure that I can use to write an argument to this object, which I've stored in its own module:

Public Sub PrintLog(obj as Object, argument as String) If writeLog = True Then obj.WriteLine argument End If End Sub

不幸的是,这不行,我不知道为什么:即使我不包括 obj 作为参数函数(因为 log 和 logWrite 被创建为全局变量),我不能调用WriteLog(String here)或调用WriteLog(log,String here。)没有错误(编译错误:参数不可选。)

Unfortunately, this doesn't work, and I'm not sure why: even if I don't include obj as an argument to the function (since log and logWrite were created as global variables), I'm not able to Call WriteLog("String here.") or Call WriteLog(log, "String here.") without an error (Compile Error: Argument Not Optional.)

是否可以获得这样一个 Sub() / code>工作,所以我可以从工作簿中的任何地方(例如在用户形式按下按钮之后)调用它,而无需定义新的 Scripting.FileSystemObject 在每个模块中?

Is it possible to get such a Sub() to work, so that I can call it from anywhere in the workbook (after a button is pressed in a userform, for example) without having to define a new Scripting.FileSystemObject in every module?

推荐答案

我认为您可以通过对代码进行一些细微的更改来解决您的问题。我尝试了以下设置:

I think that you can solve your problem by making some minor changes to your code. I tried the following setup:

记录器模块:

Option Explicit Private log As Object Public Sub initLog() Dim prompt As VbMsgBoxResult Dim fso As Object prompt = MsgBox("Would you like to log events for this session?", vbYesNo, "Log Events?") If prompt = vbYes Then Set fso = CreateObject("Scripting.FileSystemObject") Set log = fso.CreateTextFile("C:/TEST.txt", False) End If End Sub Public Sub PrintLog(argument As String) If Not log Is Nothing Then log.WriteLine argument End If End Sub Public Sub yadda() 'test PrintLog "yadda" End Sub

ThisWorkbook:

ThisWorkbook:

Private Sub Workbook_Open() initLog End Sub

更多推荐

VBA:Sub写入日志文件

本文发布于:2023-11-23 21:44:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   日志   VBA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!