Excel - 按编号和工作表名称选择列

时间:2016-05-12 09:50:37

标签: excel vba excel-vba

我在Sheet1上有4列,在Sheet2上有4列 我已将columnson sheet 1命名为:

MvarNo = 1
Mdesc = 2
Mfile = 3
Mfield = 4

其中1 = a等......

如何使用工作表名称和列号命名这些列?

由于

更新

Sub Compare()

MvarNo = 1 'Sheet1
Mdesc = 2 'Sheet1
Mfile = 3 'Sheet1
Mfield = 4 'Sheet1

XvarNo = 6 'Sheet1
Xdesc = 7 'Sheet1
Xfile = 8 'Sheet1
Xfield = 9 'Sheet1

CvarNo = 1 'Sheet2
Cdesc = 2 'Sheet2
Cfile = 3 'Sheet2
Cfield = 4 'Sheet2

'Count rows on Master Sheet (Sheet1)
MvarNoLastRow = Worksheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
MdesclastRow = Worksheets("Sheet1").Cells(Rows.Count, "B").End(xlUp).Row
 MfilelastRow = Worksheets("Sheet1").Cells(Rows.Count, "C").End(xlUp).Row
MfieldlastRow = Worksheets("Sheet1").Cells(Rows.Count, "D").End(xlUp).Row

'Count rows on Compare Sheet (Sheet2)
CvarNoLastRow = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
CdesclastRow = Worksheets("Sheet2").Cells(Rows.Count, "B").End(xlUp).Row
CfilelastRow = Worksheets("Sheet2").Cells(Rows.Count, "C").End(xlUp).Row
CfieldlastRow = Worksheets("Sheet2").Cells(Rows.Count, "D").End(xlUp).Row

For i = 2 To MvarNoLastRow
For j = 2 To CvarNoLastRow

  If Cells(i, MvarNo) = Cells(j, CvarNo) Then
  Cells(i, XvarNo).Value = "Yes"
'        If Cells(i, MvarNo) = Cells(j, CvarNo) And Cells(i, Mdesc) = Cells(j, Cdesc) And Cells(i, Mfile) = Cells(j, Cfile) And Cells(i, Mfield) = Cells(j,     Cfield) Then
'        Cells(i, XvarNo).Value = "Yes"
'        ElseIf Cells(i, MvarNo) <> Cells(j, CvarNo) And Cells(i, Mdesc) <>     Cells(j, Cdesc) And Cells(i, Mfile) <> Cells(j, Cfile) And Cells(i, Mfield) <>     Cells(j, Cfield) Then
      j = j + 1
    ElseIf j = CvarNoLastRow Then
    Cells(i, XvarNo).Value = "No"


  End If

  Next j


Next i

End Sub

此宏的原因是比较工作表1和工作表2之间的信息。 我认为&#39;从我的代码中,它实际上只是将第1页上的数据与sheet1进行比较。

2 个答案:

答案 0 :(得分:0)

这有用吗?

此处我的工作表被称为&#34;广告收入&#34;

Sub test()
    Dim lC As Long
    Dim strColNames(1 To 4) As String
    For lC = 1 To 4
        strColNames(lC) = Sheet1.Name & vbTab & Str(Cells(1, lC).Column)
    Next lC End Sub
End Sub()

enter image description here

答案 1 :(得分:0)

如果您需要获取工作表名称,则以下所有操作均可用:

=SUBSTITUTE(CELL("filename"),LEFT(CELL("filename"),FIND("]",CELL("filename"))),"")

=RIGHT(CELL("filename"),LEN(CELL("filename"))-FIND("]",CELL("filename")))    

=MID(CELL("filename"),FIND("]",CELL("filename"))+1,31)

后者有效,因为excel在命名工作表时限制为31个字符

要获取列的名称,您可以使用以下内容:

=SUBSTITUTE(MID(ADDRESS(1,CELL("col")),2,2),"$","")

=MID(SUBSTITUTE(ADDRESS(1,COLUMN(R31)),"$1",""),2,2)