简体   繁体   English

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

[英]Issue with cell navigation in Excel from Access VBA

I have a small project to get data from Access using SQL queries and write the data into an excel. 我有一个小项目,可以使用SQL查询从Access中获取数据并将数据写入Excel。 In preparation for that, I tried to do the following. 为此,我尝试执行以下操作。 The resulting output is "Hello" in (6,5) and "Hello Again" in (6,6). 结果输出是(6,5)中的“ Hello”和(6,6)中的“ Hello Again”。 The "World" gets lost. “世界”迷路了。 I am little unsure how to navigate correctly. 我不太确定如何正确导航。 Most of the other variables that you see below are declared global. 您在下面看到的大多数其他变量都声明为全局变量。

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

Because the value of iCol hasn't changed (and will not change, no matter how many times you use the .Offset method, you need to change the argument sent to the .Offset method. 因为iCol的值没有改变(并且也不会改变,所以无论您使用.Offset方法多少次,都需要更改发送到.Offset方法的参数。

Try: 尝试:

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"

Or you can explicitly refer to the row/column position and avoid .Offset altogether: 或者,您可以显式引用行/列的位置,并避免.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"

Alternatively, you can define the Cell object, and then set it as a new cell using the Offset method. 或者,您可以定义Cell对象,然后使用Offset方法将其设置为新的单元格。

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

Cell.Value = "Hello"

Set Cell = Cell.offset(0, 1)

Cell.Value = "World"

Set Cell = Cell.offset(0, 1)

Cell.Value = "Hello Again"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM