Matlab与Excel的COM接口:获取没有美元符号的范围地址

时间:2018-04-11 16:18:19

标签: matlab excel-vba com vba excel

在VBA中,range.address(0,0)或range,address。(false,false)返回没有美元符号的A1地址(在Excel VBA用语中为“相对引用”)。

尝试使用sht作为工作表对象,我得到以下内容:

K>> sht.Range('B2:C3').Address
    ans = $B$2:$C$3
K>> sht.Range('B2:C3').Address(false,false)
    ans = ''
K>> sht.Range('B2:C3').Address(0,0)
    Subscript indices must either be real positive integers or logicals.
K>> get( sht.Range('B2:C3'), 'Address' )
    ans = $B$2:$C$3
K>> get( sht.Range('B2:C3'), 'Address(0,0)' )
    Error using Interface.Microsoft_Excel_14.0_Object_Library.Range/get
K>> invoke( sht.Range('B2:C3') , 'Address', 0, 0 )
    Error using Interface.Microsoft_Excel_14.0_Object_Library.Range/invoke
K>> invoke( sht.Range('B2:C3') , 'Address', false, false )
    Error using Interface.Microsoft_Excel_14.0_Object_Library.Range/invoke
K>> methods( sht.Range('B2:C3') ) % Address is not a method
    Methods for class Interface.Microsoft_Excel_14.0_Object_Library.Range:
    Activate                ClearHyperlinks         <...snip...>
    AddComment              ClearNotes              <...snip...>
    <...snip...>
K>> get( sht.Range('B2:C3') )
            Application: [1x1 Interface.Microsoft_Excel_14.0_Object_Library._Application]
                Creator: 'xlCreatorCode'
                 Parent: [1x1 Interface.Microsoft_Excel_14.0_Object_Library._Worksheet]
              AddIndent: 0
                Address: '$B$2:$C$3'
           AddressLocal: '$B$2:$C$3'
                  Areas: [1x1 Interface.Microsoft_Excel_14.0_Object_Library.Areas]

                    <...snip...>

似乎在VBA中,Address属性返回带有隐含operator()的对象,因此可以为其指定参数(如false或0)以指定本地引用。但是,从get结果中,COM接口将Address属性视为具有单个文字字符串值的简单属性,这是一个限制。

为了避免这种限制,我不认为有一种方法可以从Matlab评估VBA表达式(例如可以在VBA编辑器的立即窗口中键入的内容)?如上所示,invoke没有这样做。

我可以通过编写表达式从地址中删除美元符号,在战术层面解决这个问题,但我想从Matlab中获取VBA的一般化方法。另外,编写战术格式化函数可以实现更嘈杂,更庞大的代码。

1 个答案:

答案 0 :(得分:0)

此答案基于the answer to another question

的语法
% Open COM interface, create new workbook, access worksheet

excel = actxserver('Excel.Application');
excel.Visible=1;
wbks = excel.Workbooks;
wbks.Add
sht = wbks.Item(1).Sheets.Item(1)

% Syntax for range address using absolute reference
sht.Range('A3.B4').Address

% Syntax for range address using relative reference
get( sht.Range('A3.B4'), 'Address', 0, 0 )

% Shut down Excel workbook and COM app object
try
   excel.DisplayAlerts = 0; % Forgo save prompt on Close
end; try
   wbk.Close
end; try
   excel.Quit % Excel process still present
end; try
   delete(excel) % Excel process disappears
end % try