如何使用循环定义此类变量 [英] how to define such variables using loop
本文介绍了如何使用循环定义此类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我遇到一个问题,在我的程序中,我使用MFC打开Excel,我想在Excel中写数字.在Excel中,A1,A2,A3 ...是一列单元格的名称,如何使用循环使以下代码更具可读性.我的意思是如何使用Ai
来表示A1,A2,A3 ...
Hi all, I come across a problem, In my program, I use MFC to open a Excel,I want to write numbers to Excel. In Excel, A1,A2,A3...are the names of a column of cells, How can I use loop to make the following code more readable. I mean how to represent A1,A2,A3...using something like Ai
range=sheet.GetRange(COleVariant("A1"),COleVariant("A1"));
range.SetValue2(COleVariant(num[1]));
range=sheet.GetRange(COleVariant("A2"),COleVariant("A2"));
range.SetValue2(COleVariant(num[2]));
...
range=sheet.GetRange(COleVariant("A30"),COleVariant("A30"));
range.SetValue2(COleVariant(num[30]));
我想这样写:
I want to write it in this way:
for(int i=1;i<=30;i++)
{
range=sheet.GetRange(COleVariant("A???"),COleVariant("A???"));
range.SetValue2(COleVariant(num[i]));
}
推荐答案
for(int i=1;i<=30;i++)
{
char cell[10];
sprintf(cell, "A%d", i);
range=sheet.GetRange(COleVariant(cell),COleVariant(cell));
range.SetValue2(COleVariant(num[i]));
}
您可以编写一个将行和列索引转换为可以传递的字符串/变体的函数.这是一个示例:
You can write a function that converts row and column indices to strings / variants that can be passed. Here is an example:
// Create cell string.
// Note that indices begin at 1!
// Size of lpszCell must be >= 8.
LPCTSTR CExcelDispatch::SetCellString(LPTSTR lpszCell, int nRow, int nCol) const
{
LPTSTR lpszOut = lpszCell;
if (--nCol > 25) // make it 0 based and check for column > "Z"
{
*lpszOut = _T('A') + static_cast<TCHAR>(nCol / 26 - 1);
++lpszOut;
nCol %= 26;
}
*lpszOut = _T('A') + static_cast<TCHAR>(nCol);
_itot(nRow, ++lpszOut, 10);
return lpszCell;
}
// Get a range of cells for a worksheet.
// Pass -1 for nEndRow and nEndCol to select a single cell.
// Note that indices start at 1!
Range CExcelDispatch::GetSheetRange(_Worksheet& Worksheet,
int nStartRow, int nStartCol,
int nEndRow /*= -1*/, int nEndCol /*= -1*/)
{
ASSERT(Worksheet.m_lpDispatch);
ASSERT(nStartRow > 0); // indices are 1 based!
ASSERT(nStartCol > 0); // indices are 1 based!
ASSERT(nEndRow > 0 || nEndCol < 0); // nEndRow must be > 0 or nEndRow and nEndCol < 0
ASSERT(nEndCol > 0 || nEndRow < 0); // nEndCol must be > 0 or nEndRow and nEndCol < 0
ASSERT(nStartCol < 26 * 26); // max. column ZZ
ASSERT(nEndCol < 26 * 26); // max. column ZZ
TCHAR lpszCell[32];
COleVariant vCell1(SetCellString(lpszCell, nStartRow, nStartCol));
COleVariant vCell2((long)DISP_E_PARAMNOTFOUND, VT_ERROR);
if (nEndRow > 0 && nEndCol > 0 &&
(nEndRow != nStartRow || nEndCol != nStartCol))
{
vCell2 = COleVariant(SetCellString(lpszCell, nEndRow, nEndCol));
}
return Worksheet.GetRange(vCell1, vCell2);
}
这篇关于如何使用循环定义此类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文