简体   繁体   English

Excel VBA和XML-清除表数据

[英]Excel VBA and XML - clear table data

I've created a spreadsheet with multiple worksheets, each containing XML mapped table elements from a number of different XML files. 我创建了一个包含多个工作表的电子表格,每个工作表均包含来自多个不同XML文件的XML映射表元素。

I'm using VBA to refresh the data by pointing to a given file name in the current directory. 我正在使用VBA通过指向当前目录中的给定文件名来刷新数据。 However, if the file doesn't exist I want it to clear any existing data in the XML table. 但是,如果文件不存在,我希望它清除XML表中的所有现有数据。

If I delete the map the data remains and the link is lost. 如果我删除地图,数据将保留并且链接丢失。

Something like (and I don't know the correct syntax): 有点像(我不知道正确的语法):

Sub ClearTables()
Dim mySheet As Worksheet
Dim myTable As ListObject

For Each mySheet In ThisWorkbook.Worksheets
    For Each myTable In mySheet.ListObjects
        'MsgBox myTable.Name
        myTable.DataBodyRange.Select
        ActiveCell.ClearContents
    Next myTable
Next mySheet
End Sub

Does anyone have any ideas as to how I could achieve this. 有谁对我如何实现这一目标有任何想法。 I'd rather not have to parameterise and set the names of nearly 50+ tables when I want them all cleared at the begging of the macro. 当我希望在宏请求时将它们全部清除时,我宁愿不必参数化和设置近50多个表的名称。

All I keep getting is an error "Object variable or With block variable not set". 我一直得到的只是一个错误“对象变量或未设置块变量”。

UPDATE: I've managed to fix this by testing for empty tables. 更新:我已经通过测试空表来解决此问题。 The problem was due to some tables being empty already. 问题是由于某些表已经为空。 The code I'm using is as follows: 我使用的代码如下:

Sub ClearTables()
Dim mySheet As Worksheet
Dim myTable As ListObject

For Each mySheet In ActiveWorkbook.Worksheets
    For Each myTable In mySheet.ListObjects
        'MsgBox myTable.Name
        'myTable.DataBodyRange.ClearContents
        If Not myTable.DataBodyRange Is Nothing Then
            myTable.DataBodyRange.ClearContents
        End If
    Next myTable
Next mySheet
End Sub

How about: 怎么样:

For Each mySheet In ThisWorkbook.Sheets
    For Each myTable In mySheet.ListObjects
        myTable.DataBodyRange.ClearContents
    Next myTable
Next mySheet

Please note that the code does not test if the object is a table... actually I'm not sure what other ListObject - class objects you might have in the worksheets. 请注意,代码不会测试对象是否为表格...实际上,我不确定工作表中可能还有其他ListObject类对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM