使用VB宏修改电子表格
时间:2020-03-05 18:49:47 来源:igfitidea点击:
我有两个电子表格...当一个电子表格以某种方式修改后,我想运行一个宏,以适当的方式修改第二个电子表格。我已经隔离了需要执行的事件(修改特定列中的任何单元格),我似乎找不到关于访问和修改另一个电子表格的任何具体信息(该电子表格位于不同的LAN中同时共享...用户可以同时访问两者)。
任何帮助将是巨大的。关于如何执行此操作或者类似操作的参考与具体的代码示例一样好。
解决方案
回答
在Excel中,我们可能只需要编写代码即可打开另一个工作表,对其进行修改,然后保存数据。
有关更多信息,请参见本教程。
稍后我将不得不编辑我的VBA,因此假装这是伪代码,但它看起来应该像这样:
Dim xl: Set xl = CreateObject("Excel.Application") xl.Open "\the\share\file.xls" Dim ws: Set ws = xl.Worksheets(1) ws.Cells(0,1).Value = "New Value" ws.Save xl.Quit constSilent
回答
我们可以在一行中打开电子表格:
Workbooks.Open FileName:="\the\share\file.xls"
并将其称为活动工作簿:
Range("A1").value = "New value"
回答
将以下内容复制到" ThisWorkbook"对象中,以查看特定更改。在这种情况下,当我们将一个数值增加到另一个数值时。
注意:我们必须使用下划线替换Workbook-SheetChange
和Workbook-SheetSelectionChange
。例如:Workbook_SheetChange
和Workbook_SheetSelectionChange
,下划线在Markdown代码中转义了。
Option Explicit Dim varPreviousValue As Variant ' required for IsThisMyChange() . This should be made more unique since it's in the global space. Private Sub Workbook-SheetChange(ByVal Sh As Object, ByVal Target As Range) ' required for IsThisMyChange() IsThisMyChange Sh, Target End Sub Private Sub Workbook-SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range) ' This implements and awful way of accessing the previous value via a global. ' not pretty but required for IsThisMyChange() varPreviousValue = Target.Cells(1, 1).Value ' NB: This is used so that if a Merged set of cells if referenced only the first cell is used End Sub Private Sub IsThisMyChange(Sh As Object, Target As Range) Dim isMyChange As Boolean Dim dblValue As Double Dim dblPreviousValue As Double isMyChange = False ' Simple catch all. If either number cant be expressed as doubles, then exit. On Error GoTo ErrorHandler dblValue = CDbl(Target.Value) dblPreviousValue = CDbl(varPreviousValue) On Error GoTo 0 ' This turns off "On Error" statements in VBA. If dblValue > dblPreviousValue Then isMyChange = True End If If isMyChange Then MsgBox ("You've increased the value of " & Target.Address) End If ' end of normal execution Exit Sub ErrorHandler: ' Do nothing much. Exit Sub End Sub
如果我们希望基于此更改另一个工作簿,我会考虑检查该工作簿是否已首先打开...或者甚至更好地设计一种解决方案,可以批量处理所有更改并立即进行。根据收听情况不断更改另一个电子表格可能会很痛苦。
回答
在玩了一段时间之后,我发现迈克尔的伪代码是最接近的,但是这是我的做法:
Dim xl As Excel.Application Set xl = CreateObject("Excel.Application") xl.Workbooks.Open "\owghome1\bennejm$\testing.xls" xl.Sheets("Sheet1").Select
然后,操作表格...也许像这样:
xl.Cells(x, y).Value = "Some text"
完成后,请使用以下几行内容完成操作:
xl.Workbooks.Close xl.Quit
如果进行了更改,将在关闭文件之前提示用户保存文件。可能有一种自动保存的方法,但是这种方法实际上更好,因此我将其保留为原样。
感谢我们提供的所有帮助!