想要实现自动生成工作表目录,并插入对应的超级链接

阅读次数 282

各位大神,我的需求是插入一个“目录”工作表,生成对应工作表的目录,并生成对应的超级链接,代码不是很熟练,目前只能生成对应工作表的目录。请各位指教!

//这是代码 // 获取工作表

const targetSheet = Application.Sheets("工作表1")

// 获取工作表1A列

const columnA = targetSheet.Columns("A")

// 获取当前活动工作表

const activeSheet = ActiveSheet

// 获取当前工作表的索引

const activeIndex = activeSheet.Index

// 遍历所有工作表,找到工作表1

for (let i = 1; i <= Application.Sheets.Count; i++) {

  const sheet = Application.Sheets(i)

  if (sheet.Name === "工作表1") {

    // 激活工作表1

    sheet.Activate()

    console.log(当前活动工作表为:${ActiveSheet.Name})

    break

  }

}

// 遍历所有工作表,将工作表名称写入工作表1A列

for (let i = 1; i <= Application.Sheets.Count; i++) {

  const sheet = Application.Sheets(i)

  if (sheet.Name!== "工作表1") {

    // 获取当前工作表的名称

    const sheetName = sheet.Name

    // 获取当前工作表的索引

    const sheetIndex = sheet.Index

    // 将工作表名称写入工作表1A列

    const cell = columnA.Cells(sheetIndex, 1)

    cell.Value2 = sheetName

1 Answers

你好,生成工作表目录可参考如下代码:

// 工作表1为目录
const directoryName = '工作表1'
const directorySheet = Application.Sheets(directoryName)

// 遍历所有工作表,添加工作表超链接至目录的A列
for (let i = 1; i <= Application.Sheets.Count; i++) {
  const sheet = Application.Sheets(i)
  if (sheet.Name !== directoryName) {
    // 获取当前工作表的名称
    const sheetName = sheet.Name
    // 添加工作表超链接
    directorySheet.Hyperlinks.Add(Range('A' + i), '', "'" + sheetName + "'"+ '!A1', '', sheetName)
  }
}