public sub adjustdatagridcolumnwidth _
(dg as datagrid, _
adodata as adodb.recordset, _
intrecord as integer, _
intfield as integer, _
optional accforheaders as boolean)
'this procedure will adjust datagrids column width
'based on longest field in underlying source
'本程序段将基于当前数据源最长字段调整 datagrids 列宽
'dg = datagrid
'adodata = adodb.recordset
'intrecord = number of record
'intfield = number of field
'accforheaders = true or false
dim row as long, col as long
dim width as single, maxwidth as single
dim savefont as stdfont, savescalemode as integer
dim celltext as string
dim i as integer
'if number of records = 0 then exit from the sub
'如果记录数 = 0 则退出过程
if intrecord = 0 then exit sub
'save the form's font for datagrid's font
'we need this for form's textwidth method
'保存窗体字体作为 datagrid 的字体
'我们需要用它用于窗体的 textwidth 方法
set savefont = dg.parent.font
set dg.parent.font = dg.font
'adjust scalemode to vbtwips for the form (parent).
'将(父)窗体的 scalemode 属性设为 vbtwips。
savescalemode = dg.parent.scalemode
dg.parent.scalemode = vbtwips
'always from first record...
'从首记录开始
adodata.movefirst
maxwidth = 0
'tampung nilai maksimal dengan mengalikan variabel
'jumlah field dan jumlah record, untuk menentukan
'banyaknya sel yang akan diproses/disesuaikan lebarnya
'以上注释不是英文、法文、德文、西班牙文和意大利文
'但从上下文可以看出,此处用记录数和字段数的乘积作为进度条的最大值
maks = intfield * intrecord
'inisialisasi nilai maksimal progressbar
'初始化进度条
frmadocode2.prgbar1.visible = true
frmadocode2.prgbar1.max = maks
'we begin from the first column until the last column
'从第一列至最后一列
for col = 0 to intfield - 1
'tampilkan nama field/kolom yg sedang diproses
'显示字段(列)名
frmadocode2.lblfield.caption = _
"column: " & dg.columns(col).datafield
adodata.movefirst
'optional param, if true, set maxwidth to
'width of dg.parent
'可选参数,如果为真,设置最大宽度为窗体宽度
if accforheaders then
maxwidth = dg.parent.textwidth(dg.columns(col).text) + 200
end if
'repeat from first record again after we have
'finished process the last record in
'former column...
'在完成上一列最后一条记录后再次从首记录开始
adodata.movefirst
for row = 0 to intrecord - 1
'get the text from the datagrid's cell
'从 datagrid 单元格得到文本
if intfield = 1 then
else 'if number of field more than one
celltext = dg.columns(col).text
end if
'fix the border...
'not for "multiple-line text"...
width = dg.parent.textwidth(celltext) + 200
'update the maximum width if we found
'the wider string...
if width > maxwidth then
maxwidth = width
dg.columns(col).width = maxwidth
end if
'process next record...
adodata.movenext
doevents
'counter bertambah satu, dst
i = i + 1
frmadocode2.lblangka.caption = _
"finished " & format((i / maks) * 100, "0") & "%"
doevents
frmadocode2.prgbar1.value = i
doevents
next row
'change the column width...
dg.columns(col).width = maxwidth 'kolom terakhir!
next col
'change the datagrid's parent property
set dg.parent.font = savefont
dg.parent.scalemode = savescalemode
'if finished, then move pointer to first record again
adodata.movefirst
sleep 100
resetprogressbar
end sub 'end of adjustdatagridcolumnwidth