热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

通过构造跟进VBA继承,构造函数不工作?-Follow-UptoVBAinheritanceviaconstruction,constructornotworking?

Thisisafollow-uptothisquestion.这是这个问题的后续行动。Heresmyusecase:IwanttocomparetwoExcel

This is a follow-up to this question.

这是这个问题的后续行动。

Here's my use case: I want to compare two Excel files cell-by-cell and highlight the cells that are different. Each file will have a few sheets and each sheet will have a few columns, each with a header and a few values (as typical). Here is my draft activity diagram for the comparison code:

这是我的用例:我希望逐个单元地比较两个Excel文件并突出显示不同的单元格。每个文件都有几张纸,每张纸都有几列,每列都有一个标题和几个值(典型值)。这是比较代码的草稿活动图:

Activity Diagram

And here is my draft class diagram:

这是我的草图类图:

Class Diagram

My goal is to make VBA less cumbersome for the types of things I do often (such as comparing new and old versions of spreadsheets). That is, I want it to work more like Python... In particular, I want to write code like this:

我的目标是让VBA不那么繁琐(我比较新旧版本的电子表格)。也就是说,我希望它的工作方式更像Python ...特别是,我想编写这样的代码:

For Each Sheet1 In File1
    Name1 = Sheet1.Name
    If File2.sheet_dict.Exists(Name1) Then
        Sheet2 = File1.Sheets(File2.sheet_dict(Name1))
        Sheet2.Checked = True
        For Each Col1 In Sheet1.cols
            hdr = Col1.Header
            If Sheet2.header_dict.Exists(hdr) Then
                Col2 = Sheet2.cols(Sheet2.header_dict(hdr))
                Col2.Checked = True
                For Each Val1 In Col1.Vals
                    Val2 = Col2.Vals(Val1.row_number)
                    Val2.Checked = True
                    If Not Val1.Match(Val2) Then
                        Val1.formatBad()
                        Val2.formatBad()
                    End If
                Next Val1
                For Each Val2 In Col2.Vals
                    If Not Val2.Checked Then
                        Val2.formatBad
                    End If
                Next Val2
            Else
                Col1.formatBad()
            End If
        Next Col1
        For Each Col2 In File2.cols
            If Not Col2.Checked Then
                Col2.formatBad
            End If
        Next Col2
    Else
        Sheet1.formatBad()
    End If
Next Sheet1

For Each Sheet2 In File2
    If Not Sheet2.Checked Then
        Sheet2.formatBad()
    End If
Next Sheet2

Of course I'd have load all the data into the objects first, but you get the idea. Is it crazy to try to do something like this in VBA?

当然我先将所有数据加载到对象中,但是你明白了。尝试在VBA中做这样的事情是疯了吗?

1 个解决方案

#1


1  

It's not crazy to want to use the object oriented language features of VBA but the use case you're giving isn't that far removed from the built-in objects that excel already provides and so it isn't clear how much you'll gain from the complexity you'll be adding to get it. There's a fair bit of power to be harnessed in excel vba but it's best to play off of it's strengths whenever you can.

想要使用VBA的面向对象语言功能并不疯狂,但是你提供的用例与excel已经提供的内置对象相差不远,因此不清楚你将使用多少从你将要添加的复杂性中获益。在excel vba中可以利用相当大的力量,但最好尽可能地发挥它的优势。

You could just as easily colorize differing cells more efficiently by using the code at the end of this post - obviously not to do all that you intend but clearly something that doesn't require resorting to OO for single columns and rows.

通过使用本文末尾的代码,您可以更轻松地更好地着色不同的单元格 - 显然不是要完成您想要的所有操作,但显然不需要针对单个列和行使用OO。

Excel and vba are quite different than what programmers are used to coming from something like python that provide full class inheritance. With VBA you're stuck with only having interface inheritance which will allow you to reuse code. But if you're not careful you could very easily end up with a lot of stub code that you have to copy from class to class just to be able to satisfy the interface you want your classes to implement.

Excel和vba与程序员习惯于提供完全类继承的python之类的东西完全不同。使用VBA,您只能使用接口继承,这将允许您重用代码。但是如果你不小心你可能很容易得到很多存根代码,你必须从一个类复制到另一个类,以便能够满足你希望你的类实现的接口。

There's also another thing you definitely have to wrap your head around coming from a conventional OO language and that's how much data you replicate in your in-memory objects as opposed to just leaving on a worksheet and accessing them as required. There's a natural tendancy to want to load everything into an object and manipulate from there - but it's an urge you should really think twice about in this environment.

还有一件事你必须要从传统的OO语言中解决这个问题,那就是你在内存中的对象中复制了多少数据,而不是只是留在工作表上并根据需要访问它们。想要将所有东西加载到对象中并从那里进行操作是一种自然的趋势 - 但是在这种环境中你应该真正考虑过三次。

If you have an existing server back-end that will validate the data that moves between your worksheets and a database then at least you have a way of segregating normal MVC concerns. In effect you'd be using excel as a sort of web page with the additional functionality that spreadsheet users love. If you don't have a back-end then you really have to be very careful about validating your models and data in this environment. You should get used to the idea of protecting the worksheet except for those cells that users will have to input data into (assuming you are writing code to benefit others than just yourself). In fact it's a good idea to color the input cells and the calculated cells with distinct colors to highlight this difference. The latter should be protected whereas the former where needed can trigger events that will validate input and update the model state (and ideally work with a back-end if you've got one).

如果您有一个现有的服务器后端,它将验证在工作表和数据库之间移动的数据,那么至少您可以分离正常的MVC问题。实际上,您将使用excel作为一种具有电子表格用户喜爱的附加功能的网页。如果您没有后端,那么您必须非常小心地在此环境中验证模型和数据。您应该习惯保护工作表的想法,除了那些用户必须输入数据的单元格(假设您编写代码以使其他人受益而不仅仅是您自己)。事实上,使用不同颜色为输入单元格和计算单元格着色是一个好主意,以突出显示这种差异。后者应该受到保护,而前者在需要时可以触发将验证输入并更新模型状态的事件(如果有的话,最好使用后端工作)。

Protecting cells also allows you to hide state information in a well-defined sections of the worksheet that can be used to reference back to working objects. In fact good use cases are those that segregate well defined cell blocks as an user interface to specific class instances.

保护单元格还允许您在工作表的明确定义的部分中隐藏状态信息,这些部分可用于引用回工作对象。实际上,良好的用例是将明确定义的单元块隔离为特定类实例的用户界面的用例。

Where possible you should use ranges to reference sections on the same worksheet and on others. Named ranges are your friend here. Data validated lists are also very helpful for contiguous data and should be used whenever possible as they are very efficient at what they do. For non-contiguous data sets that are limited in size, you can use ActiveX combo-boxes which can reference in-memory object instances if their event handlers are passed an id unique to the latter.

在可能的情况下,您应该使用范围来引用同一工作表和其他工作表上的部分。命名范围是你的朋友。经过数据验证的列表对于连续数据也非常有用,应该尽可能使用它们,因为它们非常有效。对于大小有限的非连续数据集,您可以使用ActiveX组合框,如果它们的事件处理程序被传递给后者唯一的id,则它们可以引用内存中对象实例。

When checking for event changes, you should be careful of the Worksheet_Change polling that you'll see a lot of examples of on the web. This can chew up a fair bit of time if you aren't careful.

在检查事件更改时,您应该注意Worksheet_Change轮询,您将在Web上看到很多示例。如果你不小心,这可能会花费相当多的时间。

To summarize: use the whatever power you can harness from excel and refrain from re-inventing wheels.

总结一下:使用excel可以利用的任何功率,并避免重新发明轮子。

' Compares the sheet 1 of the workbook you're in
' with sheet1 of the workbook file in 'Filename'
' and colors the cells that differ between the two.
Sub compare_workbooks_sheet1()
    Dim Filename As String
    Filename = "C:\MyBook.xlsm"

    Dim wrkbk1 As Workbook
    Set wrkbk1 = Workbooks.Open(Filename:=Filename)

    Dim sht1 As Worksheet ' worksheet you're in
    Dim sht2 As Worksheet ' worksheet you've opened to compare
    Set sht1 = wrkbk1.Worksheets("Sheet1")
    Set sht2 = ThisWorkbook.Worksheets("Sheet1")

    Dim row As Long, col As Long
    With sht2
      For row = 1 To sht1.UsedRange.Rows.Count
          For col = 1 To sht1.UsedRange.Columns.Count
              If sht1.Cells(row, col) <> sht2.Cells(row, col) Then
                  .Cells(row, col).Interior.ColorIndex = 5
              End If
          Next
      Next
    End With

    wrkbk1.Close

End Sub

推荐阅读
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 本文介绍了Python对Excel文件的读取方法,包括模块的安装和使用。通过安装xlrd、xlwt、xlutils、pyExcelerator等模块,可以实现对Excel文件的读取和处理。具体的读取方法包括打开excel文件、抓取所有sheet的名称、定位到指定的表单等。本文提供了两种定位表单的方式,并给出了相应的代码示例。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文介绍了如何使用python从列表中删除所有的零,并将结果以列表形式输出,同时提供了示例格式。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • 本文详细介绍了GetModuleFileName函数的用法,该函数可以用于获取当前模块所在的路径,方便进行文件操作和读取配置信息。文章通过示例代码和详细的解释,帮助读者理解和使用该函数。同时,还提供了相关的API函数声明和说明。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • Linux服务器密码过期策略、登录次数限制、私钥登录等配置方法
    本文介绍了在Linux服务器上进行密码过期策略、登录次数限制、私钥登录等配置的方法。通过修改配置文件中的参数,可以设置密码的有效期、最小间隔时间、最小长度,并在密码过期前进行提示。同时还介绍了如何进行公钥登录和修改默认账户用户名的操作。详细步骤和注意事项可参考本文内容。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
author-avatar
黄河豚
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有