如何从另一个工作表中外部引用的单元格中获取工作表名称

如何从另一个工作表中外部引用的单元格中取出工作表名称

工作表WS1中的单元格B1显示工作表WS2引用的单元格RefCell的值。

如何显示WS1中单元格A1 RefCell存在的工作表?

像这样的事情是我需要发生的事情:

  __________________________________ |_______|___A____|___B____|___C____| |___1___|__Pets__|__Dog___|________| |___2___|__Fruit_|__Apple_|________| *Column B contains referenced values from other worksheets (within the same workbook). *The value in Column A detects the worksheet name of the value in Column B. 

这可以在VBA中实现吗? 如何实施?

你可以使用

 Sub main() Dim cell As Range For Each cell In Range("B2", Cells(Rows.Count, 2).End(xlUp)).SpecialCells(xlCellTypeFormulas) '<--| loop through column B cells with formulas found from row 2 down to last not empty one cell.Offset(, -1) = Split(Replace(cell.Formula, "=", ""), "!")(0) '<--| extract worksheet name out of current cell formula and write it in corresponding column A cell Next End Sub 

因为参考在单元格中存储为公式。

前B2细胞将有公式=宠物!refcell

所以你可以做的是获得公式使用instr函数来获取表名的长度,并使用左边获取表名并将其分配给单元格

 B_formaula= str(sheet1.range("B2").formula) st_name=left(B_formula,instr(1,B_formula,"!",vbbinarycompare)-1) sheet1.range("A2").value=st_name 

我希望这有帮助。

 sub st_name() dim ws as worksheet set ws=thisworkbook.sheets(1) irow=ws.range("B1:B"& rows.count).end(xlup).row for i = 1 to irow B_formaula= str(ws.range("B"& i).formula) st_name=left(B_formula,instr(1,B_formula,"!",vbbinarycompare)-1) ws.range("A"& i).value=st_name next i end sub 

这个子程序将检查从第1行到最后一行的b列中的所有值,并将表格名称添加到列A.

我还没有testing过的代码。 尝试代码,如果任何错误恢复。