开发者

Insert Row in the excel

开发者 https://www.devze.com 2023-01-01 17:55 出处:网络
I\'m populating the data from ms access to excel through VBA. My db contains a number of group detail i want to separate the group members during the population time the problem is that at the end of

I'm populating the data from ms access to excel through VBA. My db contains a number of group detail i want to separate the group members during the population time the problem is that at the end of the each group i wants to insert 2 rows in the excel sheet I'm using the below mentioned code but I does not work is any possible?

Dim 开发者_如何学PythonvarConnection
Dim varSQL
Dim cal, cal1, x


   varConnection = "ODBC; DSN=MS Access Database;DBQ=table.accdb; Driver={Driver do Microsoft Access (*.accdb)}"


   varSQL = "SELECT leftman.Productname,leftman.Description,leftman.SULM,leftman.MTR,leftman.meter1 FROM leftman INNER JOIN Product ON leftman.gid = Product.Productname ORDER BY Product.ID, leftman.ID"
   With ActiveSheet.QueryTables.Add(Connection:=varConnection, Destination:=ActiveSheet.Range("B4"))
           .CommandText = varSQL
           .Name = "Query-39008"
           .Refresh BackgroundQuery:=False

   End With
   x = Range("J5", Range("J5").End(xlDown)).Rows.Count

    k1 = 5
    k2 = 6
    For i = 0 To x
    s = k1 + i
    s1 = k2 + i

   If Range("J" & s & "").Value = Range("J" & s1 & "").Value Then
   msgbox "same group"

   Else

   Range("J" & s & "").Select
   ActiveCell.Offset(1).EntireRow.Insert
   ActiveCell.Offset(1).EntireRow.Insert
   k1 = 5 + 2
   k2 = 6 + 2

   End If
   Next i

first i retrieve the data in groupwise from access X is my row count K1 is cell 1 and K2 is cell2 i am comparing the cell 1 with cell 2 through looping if the data is not

match then it is consider an another group so after that cell i wants to insert the 2 rows


You can work back ways:

x = Range("J5", Range("J5").End(xlDown)).Rows.Count

For i = x To 5 Step -1
    s = i
    s1 = i - 1

    If Range("a" & s & "").Value = Range("a" & s1 & "").Value Then
        MsgBox "same group"

    Else

        Range("a" & s & "").Select
        ActiveCell.EntireRow.Insert
        ActiveCell.EntireRow.Insert

    End If
Next i


In my experience the 'Select' function can be unreliable. You can avoid it by using the following:

.Rows(s).Insert Shift:=xlDown

assuming I am understanding correctly that 's' is the row number.


  Range("a" & s & "").Select
Selection.Insert Shift:=xlDown
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号