Excel vba 报告

Excel vba report

我正在用 vb6 构建一个 excel 报告。我正在做的是遍历记录集并将文本插入单元格。我正在尝试查看是否有办法动态合并中心 2 单元格,并在其周围放置边框。这就是我的代码的样子....

Do While Not g_RS.EOF
    xlSheetInsurance.Cells(xlRow, xlCol).Value = g_RS("Label")
    xlSheetInsurance.Cells(xlRow + 1, xlCol).Value = " Count Sales "
    xlSheetInsurance.Cells(xlRow + 1, xlCol + 1).Value = "Count Buys "
     xlCol = xlCol + 2
    g_RS.MoveNext
 Loop

所以 'label' 每隔一列插入一次。在标签下方,我插入了 COUNT SALES 和 COUNT BUYS,所以基本上我试图获取 LABEL 的值,将其合并并居中放置在两个单元格上,这样它下面的 2 列看起来就像它们属于标签 - 因为我我插入了很多标签,我希望它看起来有点专业。

编辑: 我创建了宏,但我似乎做错了什么

xlSheetInsurance.Cells(xlRow, xlCol).Value = g_RS("Label")
xlSheetInsurance.Range(xlCol, xlCol + 1).Select
With Selection
    .HorizontalAlignment = xlGeneral
    .VerticalAlignment = xlBottom
End with

所以我将其包含在 LABEL 下方,它给我一个错误“METHOD Range of object Worksheet failed

Range() 方法接受字符串参数或其他有效的 Range 对象。看起来 xlRowxlCol 是无法提供给 Range() 方法的数值。

尝试更改为 Cells(),它分别采用 rowcolumn 的数字参数。

xlSheetInsurance.Cells(xlCol, xlCol + 1).Select

此外,没有必要以这种方式 select 一个对象,因为您可以直接访问它的属性和方法。考虑到这一点,您的代码可以重写为:

With xlSheetInsurance.Cells(xlRow, xlCol)
    .Value = g_RS("Label")
    With .Offset(1, 0)
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
    End With
End with
Do While Not g_RS.EOF
    With xlSheetInsurance.Cells(xlRow, xlCol)

        .Value = g_RS("Label")
        .Offset(1, 0).Value = " Count Sales "
        .Offset(1, 1).Value = "Count Buys "

        With .Resize(1, 2)
            .Merge
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlBottom
            .Borders.Weight = xlThin
        End With

    End With

    xlCol = xlCol + 2
    g_RS.MoveNext
Loop