2017-05-04 73 views
0

首先非常感谢,对于我在过去在其他主题中发现的非常好的答案。MatLab:利用Excel动态地通过单元格进行迭代COM加载项

我们一个新的挑战:

我目前正在与COM加载项在Matlab的工作,也就是我读一个Excel工作簿,并提取颜色属性:

excelapp = actxserver('Excel.Application'); %connect to excel 
workbook = excelapp.Workbooks.Open('Solutions.xls');   
worksheet = workbook.Sheets.Item(1);       
ColorValue_Solutions=worksheet.Range('N2').Interior.Color; 

现在,我想要对范围A1到J222的单元格执行此操作,为此我希望通过Range属性进行动态循环,让程序逐个读取每个单元格,然后取出颜色特性。例如:

Columns = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}; 

for j = 1:length(Columns)   
    for i = 1:222 

worksheet.(char(strcat('Range(''',Columns(j), num2str(i), ''')'))).Interior.Color 

    end 
end 

然而,这将导致一个错误:

Undefined function or variable 'Range('A1')'. 

我想这个问题是在解释的字符串与包含字符串的组合,即,范围(“A1”) 。

任何帮助,非常感谢。

回答

0

前段时间我问了一个类似的问题。 Check it out,也许你会发现它有帮助。

下面的代码应该做你想要什么:

你可以看到如何Interior.Color属性是从每一个细胞通过首次得到一个Cell对象,然后访问该CellInterior对象,并终于得到了Color属性提取那个Interior对象。 Color属性是由Microsoft定义的颜色整数(您可以了解更多herehere),我将该值存储在矩阵(M)中。为了通过指定范围的单元重复这个过程,我使用了一个嵌套循环,就像你已经做的那样。一旦该过程完成,我将显示M的内容。

excelapp = actxserver('Excel.Application'); % Start Excel as ActiveX server. 
workbook = excelapp.Workbooks.Open('Solutions.xls'); % Open Excel workbook. 
worksheet = workbook.Sheets.Item(1);   % Get the sheet object (sheet #1). 

ncols = 10;    % From column A to J. 
nrows = 222;   % From row 1 to 222. 
M(nrows, ncols) = 0; % Preallocate matrix M. 

for col = 1:ncols        % Loop through every column. 
    for row = 1:nrows       % Loop through every row. 
     cell = get(worksheet, 'Cells', row, col); % Get the cell object. 
     interior = cell.Interior;    % Get the interior object. 
     colorint = get(interior, 'Color');  % Get the color integer property. 
     M(row, col) = colorint;    % Store color integer in matrix M. 
    end 
end 

disp(M); % Display matrix M with the color integer information. 

请记住在完成后关闭连接。你可以学习如何去做herehere

+0

非常感谢!这是完美的。 –