从Access VBA在Excel中进行单元格导航问题

时间:2014-02-03 18:01:10

标签: excel vba

我有一个小项目,可以使用SQL查询从Access获取数据,并将数据写入excel。为此做准备,我试图做到以下几点。得到的输出在(6,5)中为“Hello”,在(6,6)中为“Hello Again”。 “世界”迷失了。我不确定如何正确导航。您在下面看到的大多数其他变量都被声明为全局变量。

Sub enterDataInCell()

Dim Cell As Object

Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False

Set wb = xlApp.Workbooks.Open("H:\Documents\Misc-Work\BU\test.xlsx")

Set ws = wb.Sheets(1)

irow = 6
icol = 5

Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol)

Cell.Value = "Hello"

Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol).offset(0, 1)

Cell.Value = "World"

Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol).offset(0, 1)

Cell.Value = "Hello Again"

wb.Save
wb.Close
xlApp.DisplayAlerts = True

Set wb = Nothing
Set xlApp = Nothing
Set Cell = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

因为iCol的值没有改变(并且不会改变,无论您使用.Offset方法多少次,都需要更改发送到{{1}的参数方法。

尝试:

.Offset

或者您可以明确引用行/列位置并完全避免Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol) Cell.Value = "Hello" Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol).offset(0, 1) Cell.Value = "World" Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol).offset(0, 2) Cell.Value = "Hello Again"

.Offset

或者,您可以定义Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol) Cell.Value = "Hello" Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol + 1) Cell.Value = "World" Set Cell = xlApp.Workbooks(1).Activesheet.cells(irow, icol + 2) Cell.Value = "Hello Again" 对象,然后使用Cell方法将其设置为新单元格。

Offset